跳到主要内容

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

提交记录
新增internal/cliconversation/activity.go+73 −0看文件
@@ -0,0 +1,73 @@
1新增:package cliconversation
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "strings"
6新增:)
7新增:
8新增:// ToolActivity is a display-only summary. Command bodies, file contents and
9新增:// tool outputs stay in the CLI transcript. Approval has a separate protocol.
10新增:type ToolActivity struct {
11新增: ID string `json:"id"`
12新增: Name string `json:"name"`
13新增: Detail string `json:"detail,omitempty"`
14新增: Status string `json:"status"`
15新增:}
16新增:
17新增:func updateTools(tools []ToolActivity, role string, line []byte) ([]ToolActivity, bool) {
18新增: var msg struct {
19新增: Message struct {
20新增: Content []struct {
21新增: Type string `json:"type"`
22新增: ID string `json:"id"`
23新增: Name string `json:"name"`
24新增: Input map[string]json.RawMessage `json:"input"`
25新增: ToolUseID string `json:"tool_use_id"`
26新增: IsError bool `json:"is_error"`
27新增: } `json:"content"`
28新增: } `json:"message"`
29新增: }
30新增: if json.Unmarshal(line, &msg) != nil {
31新增: return tools, false
32新增: }
33新增: changed := false
34新增: for _, b := range msg.Message.Content {
35新增: if role == "user" && b.Type == "tool_result" {
36新增: for i := range tools {
37新增: if tools[i].ID == b.ToolUseID && tools[i].Status == "called" {
38新增: tools[i].Status = "completed"
39新增: if b.IsError {
40新增: tools[i].Status = "failed"
41新增: }
42新增: changed = true
43新增: break
44新增: }
45新增: }
46新增: }
47新增: if role != "assistant" || (b.Type != "tool_use" && b.Type != "server_tool_use") || !toolNamePattern.MatchString(b.Name) || b.ID == "" || len(b.ID) > 128 || len(tools) >= 64 {
48新增: continue
49新增: }
50新增: duplicate := false
51新增: for _, item := range tools {
52新增: if item.ID == b.ID {
53新增: duplicate = true
54新增: break
55新增: }
56新增: }
57新增: if duplicate {
58新增: continue
59新增: }
60新增: detail := ""
61新增: for _, key := range []string{"description", "subject", "file_path", "pattern", "query", "skill", "subagent_type"} {
62新增: var value string
63新增: if json.Unmarshal(b.Input[key], &value) == nil && strings.TrimSpace(value) != "" {
64新增: runes := []rune(strings.TrimSpace(value))
65新增: detail = string(runes[:min(len(runes), 160)])
66新增: break
67新增: }
68新增: }
69新增: tools = append(tools, ToolActivity{ID: b.ID, Name: b.Name, Detail: detail, Status: "called"})
70新增: changed = true
71新增: }
72新增: return tools, changed
73新增:}
新增internal/cliconversation/provider.go+338 −0看文件
@@ -0,0 +1,338 @@
1新增:// Package cliconversation runs a structured Claude Code turn inside an environment
2新增:// chosen by the caller. It does not select a host, grant a project, or own sessions.
3新增:package cliconversation
4新增:
5新增:import (
6新增: "bufio"
7新增: "bytes"
8新增: "context"
9新增: "encoding/json"
10新增: "errors"
11新增: "io"
12新增: "os/exec"
13新增: "regexp"
14新增: "slices"
15新增: "strings"
16新增: "time"
17新增: "unicode/utf8"
18新增:)
19新增:
20新增:type Runner struct {
21新增: // Command must bind the supplied context to the guest process and select the
22新增: // authorized project and CLI profile. Args never contain the user's prompt.
23新增: Command func(context.Context, string, []string) (*exec.Cmd, error)
24新增: // Approve returns a decision for this specific call. It must return when
25新增: // its context is cancelled. Nil selects unattended permission denial.
26新增: Approve func(context.Context, PermissionRequest) bool
27新增: // A guest supervisor reads a JSON string on the first line, forwards the
28新增: // decoded prompt to Claude's stdin, then monitors this pipe for disconnect.
29新增: SupervisedStdin bool
30新增: OnTools func([]ToolActivity)
31新增:}
32新增:
33新增:type Turn struct {
34新增: Workspace string
35新增: SessionID string
36新增: Prompt string
37新增: Resume bool
38新增:}
39新增:
40新增:type Result struct {
41新增: Started bool
42新增: SingleTurn bool
43新增: Text string
44新增: DeniedTools []string
45新增:}
46新增:
47新增:var (
48新增: sessionIDPattern = regexp.MustCompile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
49新增: toolNamePattern = regexp.MustCompile("^[a-zA-Z0-9_.:-]{1,128}$")
50新增:)
51新增:
52新增:const (
53新增: maxPromptBytes = 64 << 10
54新增: maxEventBytes = 8 << 20
55新增: maxTextBytes = 1 << 20
56新增:)
57新增:
58新增:// Run emits assistant text deltas in order. Only a successful CLI result and
59新增:// process exit complete a turn. A caller must not retry an ambiguous failure
60新增:// automatically: the CLI can persist the user's message before emitting its result.
61新增:func (r Runner) Run(ctx context.Context, turn Turn, onText func(string)) (Result, error) {
62新增: if r.Command == nil {
63新增: return Result{}, errors.New("尚未配置 Cage 客机 Claude Code 命令")
64新增: }
65新增: if turn.Workspace == "" || !sessionIDPattern.MatchString(turn.SessionID) {
66新增: return Result{}, errors.New("Claude Code 项目或会话标识无效")
67新增: }
68新增: if len(turn.Prompt) > maxPromptBytes || !utf8.ValidString(turn.Prompt) || strings.TrimSpace(turn.Prompt) == "" {
69新增: return Result{}, errors.New("消息为空、编码无效或超过 64 KiB")
70新增: }
71新增: if err := ctx.Err(); err != nil {
72新增: return Result{}, err
73新增: }
74新增: // Keep the selected guest account's authentication and explicit user rules.
75新增: // A checked-out project must not add an allow rule or a startup hook simply
76新增: // because a paired phone starts a non-interactive turn in that directory.
77新增: args := []string{"--print", "--output-format", "stream-json", "--verbose",
78新增: "--include-partial-messages", "--safe-mode", "--setting-sources", "user",
79新增: "--disable-slash-commands"}
80新增: if r.Approve != nil {
81新增: args = append(args, "--input-format", "stream-json", "--permission-mode", "manual",
82新增: "--permission-prompts", "host", "--permission-prompt-tool", "stdio")
83新增: } else {
84新增: args = append(args, "--input-format", "text", "--permission-mode", "dontAsk")
85新增: }
86新增: if turn.Resume {
87新增: args = append(args, "--resume", turn.SessionID)
88新增: } else {
89新增: args = append(args, "--session-id", turn.SessionID)
90新增: }
91新增:
92新增: runCtx, cancel := context.WithCancel(ctx)
93新增: defer cancel()
94新增: cmd, err := r.Command(runCtx, turn.Workspace, args)
95新增: if err != nil {
96新增: return Result{}, err
97新增: }
98新增: if cmd == nil {
99新增: return Result{}, errors.New("无法准备 Claude Code 客机命令")
100新增: }
101新增: var input io.WriteCloser
102新增: if r.SupervisedStdin || r.Approve != nil {
103新增: input, err = cmd.StdinPipe()
104新增: if err != nil {
105新增: return Result{}, errors.New("无法准备 Claude Code 客机输入")
106新增: }
107新增: defer input.Close()
108新增: } else {
109新增: cmd.Stdin = strings.NewReader(turn.Prompt)
110新增: }
111新增: reader, writer := io.Pipe()
112新增: cmd.Stdout = writer
113新增: // Raw stderr and system/tool events can contain account details, environment
114新增: // paths and tool arguments. Only selected display fields enter the mobile protocol.
115新增: cmd.Stderr = io.Discard
116新增: cmd.WaitDelay = 2 * time.Second
117新增: if err := cmd.Start(); err != nil {
118新增: _ = reader.Close()
119新增: _ = writer.Close()
120新增: if err := ctx.Err(); err != nil {
121新增: return Result{}, err
122新增: }
123新增: return Result{}, errors.New("无法启动 Claude Code 客机连接")
124新增: }
125新增: if input != nil {
126新增: stop := context.AfterFunc(runCtx, func() { _ = input.Close() })
127新增: defer stop()
128新增: }
129新增: done := make(chan error, 1)
130新增: go func() {
131新增: err := cmd.Wait()
132新增: _ = writer.Close()
133新增: done <- err
134新增: }()
135新增: var approvals *approvalStream
136新增: if r.Approve != nil {
137新增: approvals = &approvalStream{ctx: runCtx, cancel: cancel, input: input, supervised: r.SupervisedStdin,
138新增: turn: turn, approve: r.Approve, pending: make(map[string]context.CancelFunc), seen: make(map[string]bool)}
139新增: startup := time.AfterFunc(time.Minute, approvals.expireInitialization)
140新增: defer startup.Stop()
141新增: err = approvals.begin()
142新增: } else if input != nil {
143新增: // Send concurrently with reading: either side can fill its OS pipe
144新增: // during startup. The supervisor keeps this stream open until exit.
145新增: sent := make(chan struct{})
146新增: go func() {
147新增: defer close(sent)
148新增: if err := json.NewEncoder(input).Encode(turn.Prompt); err != nil {
149新增: cancel()
150新增: }
151新增: }()
152新增: defer func() { _ = input.Close(); <-sent }()
153新增: }
154新增: var result Result
155新增: if err == nil {
156新增: result, err = readResult(reader, turn.SessionID, onText, approvals, r.OnTools)
157新增: }
158新增: if err != nil {
159新增: cancel()
160新增: }
161新增: _ = reader.Close()
162新增: processErr := <-done
163新增: // There may still be a pending phone decision when the child exits or
164新增: // closes its output unexpectedly. Stop it before returning the turn.
165新增: cancel()
166新增: if approvals != nil {
167新增: approvals.workers.Wait()
168新增: }
169新增: if err := ctx.Err(); err != nil {
170新增: return result, err
171新增: }
172新增: if approvals != nil {
173新增: if transportErr := approvals.failure(); transportErr != nil {
174新增: return result, transportErr
175新增: }
176新增: }
177新增: if err != nil {
178新增: return result, err
179新增: }
180新增: if processErr != nil {
181新增: return result, errors.New("Claude Code 进程退出异常,请检查客机连接、CLI 版本和登录状态")
182新增: }
183新增: return result, nil
184新增:}
185新增:
186新增:type cliEvent struct {
187新增: Type string `json:"type"`
188新增: Subtype string `json:"subtype"`
189新增: SessionID string `json:"session_id"`
190新增: ParentToolUseID *string `json:"parent_tool_use_id"`
191新增:}
192新增:
193新增:type resultEvent struct {
194新增: IsError bool `json:"is_error"`
195新增: Result string `json:"result"`
196新增: PermissionDenials []struct {
197新增: ToolName string `json:"tool_name"`
198新增: } `json:"permission_denials"`
199新增:}
200新增:
201新增:type streamEvent struct {
202新增: Event struct {
203新增: Type string `json:"type"`
204新增: Delta struct {
205新增: Type string `json:"type"`
206新增: Text string `json:"text"`
207新增: } `json:"delta"`
208新增: } `json:"event"`
209新增:}
210新增:
211新增:func readResult(reader io.Reader, sessionID string, onText func(string), approvals *approvalStream, onTools func([]ToolActivity)) (Result, error) {
212新增: var result Result
213新增: var finished bool
214新增: var emitted int
215新增: var tools []ToolActivity
216新增: scan := bufio.NewScanner(reader)
217新增: scan.Buffer(make([]byte, 32<<10), maxEventBytes)
218新增: for scan.Scan() {
219新增: line := bytes.TrimSpace(scan.Bytes())
220新增: if len(line) == 0 {
221新增: continue
222新增: }
223新增: var e cliEvent
224新增: if err := json.Unmarshal(line, &e); err != nil || e.Type == "" {
225新增: if approvals != nil && !approvals.ready {
226新增: return result, errors.New("客机 Claude Code 未返回逐次审批初始化消息,请检查 CLI 版本")
227新增: }
228新增: return result, errors.New("Claude Code 返回了无效的消息格式")
229新增: }
230新增: if e.Type == "control_request" || e.Type == "control_cancel_request" || e.Type == "control_response" {
231新增: if approvals == nil {
232新增: return result, errors.New("Claude Code 需要未配置的交互式审批")
233新增: }
234新增: if e.SessionID != "" && !strings.EqualFold(e.SessionID, sessionID) {
235新增: return result, errors.New("Claude Code 审批会话不匹配")
236新增: }
237新增: if err := approvals.control(e.Type, line); err != nil {
238新增: return result, err
239新增: }
240新增: continue
241新增: }
242新增: if e.ParentToolUseID != nil {
243新增: continue
244新增: }
245新增: if e.Type == "system" && e.Subtype == "cage_identity_changed" {
246新增: return result, errors.New("会话使用的账号、凭据或上游已变化,请恢复原配置或新建会话")
247新增: }
248新增: if e.Type == "system" && e.Subtype == "cage_identity_single_turn" {
249新增: result.SingleTurn = true
250新增: continue
251新增: }
252新增: if e.Type == "system" && e.Subtype == "cage_identity_unverified" {
253新增: return result, errors.New("无法验证本会话原先使用的上游,请检查主机配置或新建会话")
254新增: }
255新增: if e.Type == "system" && e.Subtype == "cage_identity_unverified_start" {
256新增: return result, errors.New("无法验证当前 Claude 账号或上游配置,请在电脑 Cage 检查账号和环境配置")
257新增: }
258新增: if e.Type == "system" && e.Subtype == "init" {
259新增: if !strings.EqualFold(e.SessionID, sessionID) || finished {
260新增: return result, errors.New("Claude Code 初始化了其他会话")
261新增: }
262新增: result.Started = true
263新增: continue
264新增: }
265新增: if (e.Type == "assistant" || e.Type == "user") && onTools != nil && !finished && strings.EqualFold(e.SessionID, sessionID) {
266新增: var changed bool
267新增: tools, changed = updateTools(tools, e.Type, line)
268新增: if changed {
269新增: onTools(slices.Clone(tools))
270新增: }
271新增: }
272新增: if e.Type != "stream_event" && e.Type != "result" {
273新增: continue
274新增: }
275新增: if !strings.EqualFold(e.SessionID, sessionID) || finished {
276新增: return result, errors.New("Claude Code 会话标识或结果顺序不匹配")
277新增: }
278新增: if e.Type == "stream_event" {
279新增: var stream streamEvent
280新增: if err := json.Unmarshal(line, &stream); err != nil {
281新增: return result, errors.New("Claude Code 文本事件无效")
282新增: }
283新增: if stream.Event.Type == "content_block_delta" && stream.Event.Delta.Type == "text_delta" {
284新增: text := stream.Event.Delta.Text
285新增: emitted += len(text)
286新增: if emitted > maxTextBytes {
287新增: return result, errors.New("Claude Code 回复超过 1 MiB")
288新增: }
289新增: if onText != nil && text != "" {
290新增: onText(text)
291新增: }
292新增: }
293新增: continue
294新增: }
295新增: finished = true
296新增: if approvals != nil {
297新增: if err := approvals.finish(); err != nil {
298新增: return result, err
299新增: }
300新增: }
301新增: var final resultEvent
302新增: if err := json.Unmarshal(line, &final); err != nil {
303新增: return result, errors.New("Claude Code 返回了无效的最终结果")
304新增: }
305新增: for _, denial := range final.PermissionDenials {
306新增: name := denial.ToolName
307新增: if !toolNamePattern.MatchString(name) {
308新增: name = "未知工具"
309新增: }
310新增: if !slices.Contains(result.DeniedTools, name) {
311新增: result.DeniedTools = append(result.DeniedTools, name)
312新增: }
313新增: if len(result.DeniedTools) == 64 {
314新增: break
315新增: }
316新增: }
317新增: if final.IsError || e.Subtype != "success" {
318新增: return result, errors.New("Claude Code 未完成本轮,请检查客机登录、网络和工具权限")
319新增: }
320新增: if !result.Started {
321新增: return result, errors.New("Claude Code 返回结果前未确认会话")
322新增: }
323新增: if len(final.Result) > maxTextBytes {
324新增: return result, errors.New("Claude Code 回复超过 1 MiB")
325新增: }
326新增: result.Text = final.Result
327新增: }
328新增: if scan.Err() != nil {
329新增: return result, errors.New("Claude Code 消息流中断或单条事件过大")
330新增: }
331新增: if !finished {
332新增: if approvals != nil && !approvals.ready {
333新增: return result, errors.New("客机 Claude Code 未确认逐次审批协议,请检查 CLI 版本")
334新增: }
335新增: return result, errors.New("Claude Code 未返回本轮结果,请检查客机连接、CLI 版本和登录状态")
336新增: }
337新增: return result, nil
338新增:}
新增internal/cliconversation/provider_approval.go+189 −0看文件
@@ -0,0 +1,189 @@
1新增:package cliconversation
2新增:
3新增:import (
4新增: "context"
5新增: "encoding/json"
6新增: "errors"
7新增: "io"
8新增: "sync"
9新增:)
10新增:
11新增:// Input is the complete proposed tool input. Approve receives a copy so its
12新增:// decision cannot change the arguments which are sent back to Claude Code.
13新增:type PermissionRequest struct {
14新增: Tool string
15新增: Input json.RawMessage
16新增:}
17新增:
18新增:const maxApprovalBytes = 8 << 10
19新增:const initRequestID = "cage-cli-initialize"
20新增:
21新增:// Claude Code uses the same bidirectional JSONL control protocol as its Agent
22新增:// SDK. In supervised mode a second framing layer keeps the guest process lease
23新增:// open after the CLI's input is closed at the end of a successful turn.
24新增:type approvalStream struct {
25新增: ctx context.Context
26新增: cancel context.CancelFunc
27新增: input io.WriteCloser
28新增: supervised bool
29新增: approve func(context.Context, PermissionRequest) bool
30新增: turn Turn
31新增:
32新增: mu sync.Mutex // Serializes control frames, answers, and end-of-input.
33新增: ready bool
34新增: ended bool
35新增: pending map[string]context.CancelFunc
36新增: seen map[string]bool
37新增: workers sync.WaitGroup
38新增: writeErr error
39新增:}
40新增:
41新增:func (p *approvalStream) expireInitialization() {
42新增: p.mu.Lock()
43新增: defer p.mu.Unlock()
44新增: if !p.ready && p.ctx.Err() == nil {
45新增: p.writeErr = errors.New("客机 Claude Code 未在一分钟内确认逐次审批,请检查 CLI 版本")
46新增: p.cancel()
47新增: }
48新增:}
49新增:
50新增:func (p *approvalStream) failure() error {
51新增: p.mu.Lock()
52新增: defer p.mu.Unlock()
53新增: return p.writeErr
54新增:}
55新增:
56新增:func (p *approvalStream) begin() error {
57新增: p.mu.Lock()
58新增: defer p.mu.Unlock()
59新增: if p.supervised {
60新增: if err := json.NewEncoder(p.input).Encode(map[string]bool{"stream": true}); err != nil {
61新增: return errors.New("无法开始客机审批通道")
62新增: }
63新增: }
64新增: return p.sendLocked(map[string]any{"type": "control_request", "request_id": initRequestID,
65新增: "request": map[string]any{"subtype": "initialize", "hooks": map[string]any{}}})
66新增:}
67新增:
68新增:func (p *approvalStream) sendLocked(frame any) error {
69新增: if p.supervised {
70新增: frame = map[string]any{"input": frame}
71新增: }
72新增: if err := json.NewEncoder(p.input).Encode(frame); err != nil {
73新增: p.writeErr = errors.New("Claude Code 审批通道已断开")
74新增: p.cancel()
75新增: return p.writeErr
76新增: }
77新增: return nil
78新增:}
79新增:
80新增:type controlFrame struct {
81新增: RequestID string `json:"request_id"`
82新增: Request struct {
83新增: Subtype string `json:"subtype"`
84新增: Tool string `json:"tool_name"`
85新增: Input json.RawMessage `json:"input"`
86新增: } `json:"request"`
87新增: Response struct {
88新增: Subtype string `json:"subtype"`
89新增: RequestID string `json:"request_id"`
90新增: } `json:"response"`
91新增:}
92新增:
93新增:func (p *approvalStream) control(kind string, line []byte) error {
94新增: var frame controlFrame
95新增: if err := json.Unmarshal(line, &frame); err != nil {
96新增: return errors.New("Claude Code 审批消息格式无效")
97新增: }
98新增: p.mu.Lock()
99新增: defer p.mu.Unlock()
100新增: if p.ended {
101新增: return nil
102新增: }
103新增: if kind == "control_response" {
104新增: if p.ready || frame.Response.RequestID != initRequestID || frame.Response.Subtype != "success" {
105新增: return errors.New("客机 Claude Code 无法初始化逐次审批,请检查 CLI 版本")
106新增: }
107新增: p.ready = true
108新增: return p.sendLocked(map[string]any{"type": "user", "session_id": p.turn.SessionID, "parent_tool_use_id": nil,
109新增: "message": map[string]string{"role": "user", "content": p.turn.Prompt}})
110新增: }
111新增: id := frame.RequestID
112新增: if id == "" || len(id) > 256 {
113新增: return errors.New("Claude Code 审批请求标识无效")
114新增: }
115新增: if kind == "control_cancel_request" {
116新增: if cancel := p.pending[id]; cancel != nil {
117新增: delete(p.pending, id)
118新增: cancel()
119新增: }
120新增: return nil
121新增: }
122新增: if !p.ready || p.seen[id] {
123新增: return errors.New("Claude Code 审批请求重复或未初始化")
124新增: }
125新增: if len(p.seen) >= 1024 || len(p.pending) >= 16 {
126新增: return errors.New("本轮工具请求超出容量,已停止执行")
127新增: }
128新增: p.seen[id] = true
129新增: if frame.Request.Subtype != "can_use_tool" {
130新增: return p.sendLocked(map[string]any{"type": "control_response", "response": map[string]string{
131新增: "subtype": "error", "request_id": id, "error": "Unsupported control request"}})
132新增: }
133新增: request := PermissionRequest{Tool: frame.Request.Tool, Input: frame.Request.Input}
134新增: // json.Unmarshal validated the complete frame; individual tool inputs must
135新增: // be objects. An oversized input must never become a truncated approval.
136新增: if !toolNamePattern.MatchString(request.Tool) || len(request.Input) == 0 || len(request.Input) > maxApprovalBytes || request.Input[0] != '{' {
137新增: return p.answerLocked(id, false, nil)
138新增: }
139新增: ctx, cancel := context.WithCancel(p.ctx)
140新增: p.pending[id] = cancel
141新增: p.workers.Add(1)
142新增: go func() {
143新增: defer p.workers.Done()
144新增: defer cancel()
145新增: allowed := p.approve(ctx, PermissionRequest{Tool: request.Tool, Input: append(json.RawMessage(nil), request.Input...)})
146新增: p.mu.Lock()
147新增: defer p.mu.Unlock()
148新增: if p.pending[id] == nil || ctx.Err() != nil || p.ended {
149新增: return
150新增: }
151新增: delete(p.pending, id)
152新增: _ = p.answerLocked(id, allowed, request.Input)
153新增: }()
154新增: return nil
155新增:}
156新增:
157新增:func (p *approvalStream) answerLocked(id string, allowed bool, input json.RawMessage) error {
158新增: answer := map[string]any{"behavior": "deny", "message": "Cage did not approve this tool call."}
159新增: if allowed {
160新增: answer = map[string]any{"behavior": "allow", "updatedInput": input}
161新增: }
162新增: return p.sendLocked(map[string]any{"type": "control_response", "response": map[string]any{
163新增: "subtype": "success", "request_id": id, "response": answer}})
164新增:}
165新增:
166新增:func (p *approvalStream) finish() error {
167新增: p.mu.Lock()
168新增: defer p.mu.Unlock()
169新增: p.ended = true
170新增: for _, cancel := range p.pending {
171新增: cancel()
172新增: }
173新增: if !p.ready {
174新增: return errors.New("客机 Claude Code 未确认逐次审批协议")
175新增: }
176新增: if p.writeErr != nil {
177新增: return p.writeErr
178新增: }
179新增: if p.supervised {
180新增: if err := json.NewEncoder(p.input).Encode(map[string]bool{"finish": true}); err != nil {
181新增: return errors.New("无法结束 Claude Code 客机输入")
182新增: }
183新增: return nil
184新增: }
185新增: if err := p.input.Close(); err != nil {
186新增: return errors.New("无法结束 Claude Code 输入")
187新增: }
188新增: return nil
189新增:}
新增internal/cliconversation/provider_approval_test.go+108 −0看文件
@@ -0,0 +1,108 @@
1新增:package cliconversation
2新增:
3新增:import (
4新增: "bytes"
5新增: "context"
6新增: "encoding/json"
7新增: "strings"
8新增: "testing"
9新增:)
10新增:
11新增:type approvalCapture struct{ bytes.Buffer }
12新增:
13新增:func (*approvalCapture) Close() error { return nil }
14新增:
15新增:func TestDecisionsFollowTheOriginalRequestThroughSupervisor(t *testing.T) {
16新增: ctx, cancel := context.WithCancel(context.Background())
17新增: defer cancel()
18新增: wire := new(approvalCapture)
19新增: release := make(chan struct{})
20新增: p := &approvalStream{
21新增: ctx: ctx, cancel: cancel, input: wire, supervised: true, turn: Turn{SessionID: testSessionID, Prompt: "fixture"},
22新增: pending: make(map[string]context.CancelFunc), seen: make(map[string]bool),
23新增: approve: func(ctx context.Context, r PermissionRequest) bool {
24新增: var args struct{ Command string }
25新增: if err := json.Unmarshal(r.Input, &args); err != nil {
26新增: t.Error(err)
27新增: return false
28新增: }
29新增: switch args.Command {
30新增: case "first":
31新增: <-release // A second decision may arrive first.
32新增: clear(r.Input)
33新增: return true
34新增: case "second":
35新增: return false
36新增: case "revoked":
37新增: <-ctx.Done()
38新增: return true // A late allow after CLI cancellation must have no effect.
39新增: default:
40新增: t.Error("oversized input reached the approval UI")
41新增: return false
42新增: }
43新增: },
44新增: }
45新增: if err := p.begin(); err != nil {
46新增: t.Fatal(err)
47新增: }
48新增: if err := p.control("control_response", []byte(`{"response":{"subtype":"success","request_id":"wrong-init"}}`)); err == nil {
49新增: t.Fatal("accepted an unrelated initialization reply")
50新增: }
51新增: if err := p.control("control_response", []byte(`{"response":{"subtype":"success","request_id":"cage-cli-initialize"}}`)); err != nil {
52新增: t.Fatal(err)
53新增: }
54新增: request := func(id, command string) error {
55新增: line, _ := json.Marshal(map[string]any{"request_id": id, "request": map[string]any{
56新增: "subtype": "can_use_tool", "tool_name": "Bash", "input": map[string]string{"command": command},
57新增: }})
58新增: return p.control("control_request", line)
59新增: }
60新增: for id, command := range map[string]string{"one": "first", "two": "second", "old": "revoked", "large": strings.Repeat("x", maxApprovalBytes)} {
61新增: if err := request(id, command); err != nil {
62新增: t.Fatal(err)
63新增: }
64新增: }
65新增: if err := request("one", "first"); err == nil {
66新增: t.Fatal("accepted a duplicate approval ID")
67新增: }
68新增: if err := p.control("control_cancel_request", []byte(`{"request_id":"old"}`)); err != nil {
69新增: t.Fatal(err)
70新增: }
71新增: close(release)
72新增: p.workers.Wait()
73新增: if err := p.finish(); err != nil {
74新增: t.Fatal(err)
75新增: }
76新增: lines := bytes.Split(bytes.TrimSpace(wire.Bytes()), []byte("\n"))
77新增: if string(lines[0]) != `{"stream":true}` || string(lines[len(lines)-1]) != `{"finish":true}` {
78新增: t.Fatal("supervisor did not get explicit stream start and finish")
79新增: }
80新增: decisions := map[string]string{}
81新增: for _, line := range lines[1 : len(lines)-1] {
82新增: var packet struct {
83新增: Input struct {
84新增: Type string `json:"type"`
85新增: Response struct {
86新增: ID string `json:"request_id"`
87新增: Answer struct {
88新增: Behavior string `json:"behavior"`
89新增: Updated struct{ Command string } `json:"updatedInput"`
90新增: } `json:"response"`
91新增: } `json:"response"`
92新增: } `json:"input"`
93新增: }
94新增: if err := json.Unmarshal(line, &packet); err != nil || packet.Input.Type == "" {
95新增: t.Fatalf("invalid supervisor input: %s", line)
96新增: }
97新增: if packet.Input.Type == "control_response" {
98新增: response := packet.Input.Response
99新增: if _, duplicate := decisions[response.ID]; duplicate {
100新增: t.Fatal("sent two answers for one request")
101新增: }
102新增: decisions[response.ID] = response.Answer.Behavior + ":" + response.Answer.Updated.Command
103新增: }
104新增: }
105新增: if len(decisions) != 3 || decisions["one"] != "allow:first" || decisions["two"] != "deny:" || decisions["large"] != "deny:" {
106新增: t.Errorf("approval crossed requests, accepted a late decision, or changed input: %#v", decisions)
107新增: }
108新增:}
新增internal/cliconversation/provider_test.go+270 −0看文件
@@ -0,0 +1,270 @@
1新增:package cliconversation
2新增:
3新增:import (
4新增: "bufio"
5新增: "context"
6新增: "encoding/json"
7新增: "fmt"
8新增: "net/http"
9新增: "net/http/httptest"
10新增: "os"
11新增: "os/exec"
12新增: "path/filepath"
13新增: "slices"
14新增: "strings"
15新增: "sync/atomic"
16新增: "testing"
17新增: "time"
18新增:)
19新增:
20新增:const testSessionID = "de3ac0b3-1bad-43da-88ab-d86b7af32210"
21新增:
22新增:func TestResultRequiresMatchingCompletedSession(t *testing.T) {
23新增: init := `{"type":"system","subtype":"init","session_id":"` + testSessionID + `"}` + "\n"
24新增: final := `{"type":"result","subtype":"success","session_id":"` + testSessionID + `","result":"done"}`
25新增: for _, events := range []string{
26新增: `{"type":"assistant","message":{"content":[{"type":"text","text":"partial"}]}}`,
27新增: strings.Replace(final, testSessionID, "1d2f57e6-64f9-44df-b0b4-43381e33a317", 1),
28新增: init + final + "\n" + final,
29新增: `{"type":"result","session_id":"` + testSessionID + `","is_error":true,"result":"private upstream diagnostic"}`,
30新增: } {
31新增: _, err := readResult(strings.NewReader(events), testSessionID, nil, nil, nil)
32新增: if err == nil || strings.Contains(err.Error(), "private") {
33新增: t.Fatalf("expected a sanitized failure, got %v", err)
34新增: }
35新增: }
36新增:}
37新增:
38新增:func TestIdentityFailureExplainsFirstLaunch(t *testing.T) {
39新增: result, err := readResult(strings.NewReader(`{"type":"system","subtype":"cage_identity_unverified_start"}`), testSessionID, nil, nil, nil)
40新增: if result.Started || err == nil || !strings.Contains(err.Error(), "当前 Claude 账号") || strings.Contains(err.Error(), "新建会话") {
41新增: t.Fatalf("unexpected first-launch failure: %#v %v", result, err)
42新增: }
43新增:}
44新增:
45新增:func TestSupervisedInputKeepsConnectionOpenAfterPrompt(t *testing.T) {
46新增: const prompt = "a quoted \"argument\"\non another line"
47新增: if os.Getenv("CAGE_CLI_SUPERVISOR_FIXTURE") == "1" {
48新增: input := bufio.NewReader(os.Stdin)
49新增: line, err := input.ReadBytes('\n')
50新增: var received string
51新增: if err != nil || json.Unmarshal(line, &received) != nil || received != prompt {
52新增: os.Exit(2)
53新增: }
54新增: closed := make(chan struct{})
55新增: go func() { _, _ = input.ReadByte(); close(closed) }()
56新增: select {
57新增: case <-closed:
58新增: os.Exit(3)
59新增: case <-time.After(70 * time.Millisecond):
60新增: }
61新增: fmt.Printf("{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":%q}\n", testSessionID)
62新增: fmt.Printf("{\"type\":\"result\",\"subtype\":\"success\",\"session_id\":%q,\"result\":\"ok\"}\n", testSessionID)
63新增: os.Exit(0)
64新增: }
65新增: runner := Runner{SupervisedStdin: true, Command: func(ctx context.Context, _ string, _ []string) (*exec.Cmd, error) {
66新增: cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestSupervisedInputKeepsConnectionOpenAfterPrompt$")
67新增: cmd.Env = append(os.Environ(), "CAGE_CLI_SUPERVISOR_FIXTURE=1")
68新增: return cmd, nil
69新增: }}
70新增: ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
71新增: defer cancel()
72新增: result, err := runner.Run(ctx, Turn{Workspace: t.TempDir(), SessionID: testSessionID, Prompt: prompt}, nil)
73新增: if err != nil || !result.Started || result.Text != "ok" {
74新增: t.Fatalf("supervised turn: %#v, %v", result, err)
75新增: }
76新增:}
77新增:
78新增:func TestCancelStopsRunningProcess(t *testing.T) {
79新增: if os.Getenv("CAGE_CLI_CANCEL_FIXTURE") == "1" {
80新增: fmt.Printf("{\"type\":\"stream_event\",\"session_id\":%q,\"event\":{\"type\":\"content_block_delta\",\"delta\":{\"type\":\"text_delta\",\"text\":\"started\"}}}\n", testSessionID)
81新增: time.Sleep(30 * time.Second)
82新增: os.Exit(0)
83新增: }
84新增: ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
85新增: defer cancel()
86新增: runner := Runner{Command: func(ctx context.Context, _ string, _ []string) (*exec.Cmd, error) {
87新增: cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestCancelStopsRunningProcess$")
88新增: cmd.Env = append(os.Environ(), "CAGE_CLI_CANCEL_FIXTURE=1")
89新增: return cmd, nil
90新增: }}
91新增: _, err := runner.Run(ctx, Turn{Workspace: t.TempDir(), SessionID: testSessionID, Prompt: "synthetic"}, func(string) { cancel() })
92新增: if err != context.Canceled {
93新增: t.Fatalf("cancelling a streaming turn returned %v", err)
94新增: }
95新增:}
96新增:
97新增:// CAGE_TEST_CLAUDE_CLI points to an installed official executable. This test
98新增:// drives that actual process and its real session files; only its model is a
99新增:// fixture. Bare mode and an isolated environment keep personal credentials out.
100新增:func TestRealClaudeCodeWithLocalUpstream(t *testing.T) {
101新增: binary := os.Getenv("CAGE_TEST_CLAUDE_CLI")
102新增: if binary == "" {
103新增: t.Skip("set CAGE_TEST_CLAUDE_CLI to an absolute official Claude Code executable")
104新增: }
105新增: if !filepath.IsAbs(binary) {
106新增: t.Fatal("use an absolute executable path")
107新增: }
108新增: home := t.TempDir()
109新增: project := t.TempDir()
110新增: forbidden := filepath.Join(project, "would-write.txt")
111新增: var resumed, denied atomic.Bool
112新增: upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
113新增: if req.URL.Path == "/v1/messages/count_tokens" {
114新增: w.Header().Set("Content-Type", "application/json")
115新增: fmt.Fprint(w, `{"input_tokens":64}`)
116新增: return
117新增: }
118新增: if req.URL.Path != "/v1/messages" {
119新增: http.NotFound(w, req)
120新增: return
121新增: }
122新增: var payload struct {
123新增: Model string `json:"model"`
124新增: Messages json.RawMessage `json:"messages"`
125新增: Stream bool `json:"stream"`
126新增: }
127新增: if err := json.NewDecoder(req.Body).Decode(&payload); err != nil || !payload.Stream {
128新增: http.Error(w, "expected a streaming Messages API request", http.StatusBadRequest)
129新增: return
130新增: }
131新增: history := string(payload.Messages)
132新增: w.Header().Set("Content-Type", "text/event-stream")
133新增: event := func(kind string, data any) {
134新增: body, err := json.Marshal(data)
135新增: if err != nil {
136新增: t.Errorf("fixture event: %v", err)
137新增: return
138新增: }
139新增: fmt.Fprintf(w, "event: %s\ndata: %s\n\n", kind, body)
140新增: w.(http.Flusher).Flush()
141新增: }
142新增: event("message_start", map[string]any{"type": "message_start", "message": map[string]any{
143新增: "id": "msg_synthetic_cage", "type": "message", "role": "assistant", "model": payload.Model,
144新增: "content": []any{}, "stop_reason": nil, "stop_sequence": nil,
145新增: "usage": map[string]int{"input_tokens": 64, "output_tokens": 1},
146新增: }})
147新增: stop := "end_turn"
148新增: if strings.Contains(history, "write-fixture") && !strings.Contains(history, `"tool_result"`) {
149新增: stop = "tool_use"
150新增: event("content_block_start", map[string]any{"type": "content_block_start", "index": 0,
151新增: "content_block": map[string]any{"type": "tool_use", "id": "toolu_cage", "name": "Bash", "input": map[string]any{}}})
152新增: input, _ := json.Marshal(map[string]string{"command": "printf synthetic > would-write.txt", "description": "Create a synthetic test file"})
153新增: event("content_block_delta", map[string]any{"type": "content_block_delta", "index": 0,
154新增: "delta": map[string]string{"type": "input_json_delta", "partial_json": string(input)}})
155新增: } else {
156新增: reply := "first simulated reply"
157新增: if strings.Contains(history, "resume-fixture") {
158新增: resumed.Store(strings.Contains(history, "first-fixture") && strings.Contains(history, "first simulated reply"))
159新增: reply = "second simulated reply"
160新增: }
161新增: if strings.Contains(history, "write-fixture") {
162新增: denied.Store(strings.Contains(history, `"is_error":true`))
163新增: if denied.Load() {
164新增: reply = "simulated denial received"
165新增: } else {
166新增: reply = "simulated write completed"
167新增: }
168新增: }
169新增: event("content_block_start", map[string]any{"type": "content_block_start", "index": 0,
170新增: "content_block": map[string]string{"type": "text", "text": ""}})
171新增: event("content_block_delta", map[string]any{"type": "content_block_delta", "index": 0,
172新增: "delta": map[string]string{"type": "text_delta", "text": reply}})
173新增: }
174新增: event("content_block_stop", map[string]any{"type": "content_block_stop", "index": 0})
175新增: event("message_delta", map[string]any{"type": "message_delta", "delta": map[string]any{"stop_reason": stop, "stop_sequence": nil},
176新增: "usage": map[string]int{"output_tokens": 5}})
177新增: event("message_stop", map[string]string{"type": "message_stop"})
178新增: }))
179新增: defer upstream.Close()
180新增: supervisor := os.Getenv("CAGE_TEST_CLI_SUPERVISOR")
181新增: runner := Runner{SupervisedStdin: supervisor != "", Command: func(ctx context.Context, workspace string, args []string) (*exec.Cmd, error) {
182新增: command := append([]string{binary, "--bare"}, args...)
183新增: if supervisor != "" {
184新增: python, err := exec.LookPath("python3")
185新增: if err != nil {
186新增: return nil, err
187新增: }
188新增: command = append([]string{python, "-I", supervisor, workspace}, command...)
189新增: }
190新增: cmd := exec.CommandContext(ctx, command[0], command[1:]...)
191新增: if supervisor != "" {
192新增: // Simulate SSH disconnect locally: EOF reaches the real supervisor.
193新增: // WaitDelay remains a final bound if the supervisor cannot exit.
194新增: cmd.Cancel = func() error { return nil }
195新增: }
196新增: cmd.Dir = workspace
197新增: cmd.Env = []string{
198新增: "HOME=" + home, "USERPROFILE=" + home, "CLAUDE_CONFIG_DIR=" + filepath.Join(home, "config"),
199新增: "PATH=" + filepath.Dir(binary) + string(os.PathListSeparator) + "/usr/bin" + string(os.PathListSeparator) + "/bin",
200新增: "ANTHROPIC_BASE_URL=" + upstream.URL, "ANTHROPIC_API_KEY=sk-ant-fixture-only",
201新增: "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1", "DISABLE_AUTOUPDATER=1",
202新增: "HTTPS_PROXY=http://127.0.0.1:1", "HTTP_PROXY=http://127.0.0.1:1", "NO_PROXY=127.0.0.1,localhost",
203新增: }
204新增: if systemRoot := os.Getenv("SystemRoot"); systemRoot != "" {
205新增: cmd.Env = append(cmd.Env, "SystemRoot="+systemRoot)
206新增: }
207新增: return cmd, nil
208新增: }}
209新增: ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
210新增: defer cancel()
211新增: run := func(id, prompt, want string, resume bool) Result {
212新增: t.Helper()
213新增: var live strings.Builder
214新增: result, err := runner.Run(ctx, Turn{project, id, prompt, resume}, func(delta string) { live.WriteString(delta) })
215新增: if err != nil || !result.Started || result.Text != want || live.String() != want {
216新增: t.Fatalf("turn %s: result=%q live=%q err=%v", prompt, result.Text, live.String(), err)
217新增: }
218新增: return result
219新增: }
220新增: run(testSessionID, "first-fixture", "first simulated reply", false)
221新增: run(testSessionID, "resume-fixture", "second simulated reply", true)
222新增: if !resumed.Load() {
223新增: t.Fatal("resumed CLI did not send the first exchange to the local provider")
224新增: }
225新增: result := run("93b18ece-8eab-4c7e-b970-c3652252b7c4", "write-fixture", "simulated denial received", false)
226新增: if !denied.Load() || !slices.Contains(result.DeniedTools, "Bash") {
227新增: t.Fatalf("missing permission denial: upstream observed denial=%t, result=%#v", denied.Load(), result)
228新增: }
229新增: if _, err := os.Stat(forbidden); !os.IsNotExist(err) {
230新增: t.Fatalf("denied tool changed the workspace: %v", err)
231新增: }
232新增: var approvals atomic.Int32
233新增: answer := func(allow bool) func(context.Context, PermissionRequest) bool {
234新增: return func(_ context.Context, request PermissionRequest) bool {
235新增: approvals.Add(1)
236新增: var proposed struct{ Command string }
237新增: if request.Tool != "Bash" || json.Unmarshal(request.Input, &proposed) != nil || proposed.Command != "printf synthetic > would-write.txt" {
238新增: t.Errorf("unexpected approval request: %s, %s", request.Tool, request.Input)
239新增: return false
240新增: }
241新增: if _, err := os.Stat(forbidden); !os.IsNotExist(err) {
242新增: t.Errorf("command ran before the decision: %v", err)
243新增: return false
244新增: }
245新增: // The approval UI cannot substitute different arguments, even if it
246新增: // accidentally mutates its raw JSON while preparing a preview.
247新增: clear(request.Input)
248新增: return allow
249新增: }
250新增: }
251新增: runner.Approve = answer(false)
252新增: run("24816c82-cf57-4ec3-b8c0-05dc70614440", "write-fixture", "simulated denial received", false)
253新增: pending, stop := context.WithCancel(ctx)
254新增: defer stop()
255新增: runner.Approve = func(approvalCtx context.Context, _ PermissionRequest) bool {
256新增: stop()
257新增: <-approvalCtx.Done()
258新增: return true
259新增: }
260新增: result, err := runner.Run(pending, Turn{project, "0ca69e7b-2661-4b81-b966-f2589547933c", "write-fixture", false}, nil)
261新增: if err != context.Canceled || !result.Started {
262新增: t.Fatalf("cancel during pending tool approval: %#v, %v", result, err)
263新增: }
264新增: runner.Approve = answer(true)
265新增: run("8c0d77d3-cb3e-43b2-9114-62cb05c5ebc4", "write-fixture", "simulated write completed", false)
266新增: bytes, err := os.ReadFile(forbidden)
267新增: if err != nil || string(bytes) != "synthetic" || approvals.Load() != 2 {
268新增: t.Fatalf("expected one approved write after exactly two decisions: %q, %v, decisions=%d", bytes, err, approvals.Load())
269新增: }
270新增:}
新增internal/clipboardfiles/archive.go+222 −0看文件
@@ -0,0 +1,222 @@
1新增:// Package clipboardfiles streams selected ordinary files between guest systems.
2新增:// It has no host/guest process or authentication policy; callers own the selection.
3新增:package clipboardfiles
4新增:
5新增:import (
6新增: "archive/tar"
7新增: "errors"
8新增: "io"
9新增: "os"
10新增: "path/filepath"
11新增: "strings"
12新增:)
13新增:
14新增:const FileLimit int64 = 2 << 30
15新增:const SelectionLimit = 100
16新增:
17新增:// LinkCachedFiles groups already frozen guest-cache files for one native file
18新增:// chooser without copying every attachment again. GUI callers validate ownership.
19新增:func LinkCachedFiles(paths []string) (result []string, err error) {
20新增: if len(paths) == 0 || len(paths) > SelectionLimit {
21新增: return nil, errors.New("请选择 1 至 100 个文件")
22新增: }
23新增: root, err := os.MkdirTemp("", "cage-clipboard-")
24新增: if err != nil {
25新增: return nil, err
26新增: }
27新增: defer func() {
28新增: if err != nil {
29新增: _ = os.RemoveAll(root)
30新增: }
31新增: }()
32新增: for _, source := range paths {
33新增: name := filepath.Base(source)
34新增: info, err := os.Lstat(source)
35新增: if err != nil || !filepath.IsAbs(source) || !strings.HasPrefix(filepath.Base(filepath.Dir(source)), "cage-clipboard-") || !validName(name) || !info.Mode().IsRegular() || info.Size() > FileLimit {
36新增: return nil, errors.New("附件缓存文件无效")
37新增: }
38新增: target := filepath.Join(root, name)
39新增: if err := os.Link(source, target); err != nil {
40新增: return nil, errors.New("无法准备附件选择,请核对文件名是否重复")
41新增: }
42新增: linked, err := os.Lstat(target)
43新增: if err != nil || !linked.Mode().IsRegular() || !os.SameFile(info, linked) {
44新增: return nil, errors.New("附件缓存已变化,请重新选择文件")
45新增: }
46新增: result = append(result, target)
47新增: }
48新增: return result, nil
49新增:}
50新增:
51新增:// Save receives one file into a newly owned cache directory. The caller can
52新增:// publish the returned path only after the complete bounded write succeeds.
53新增:func Save(input io.Reader, name string) (path string, err error) {
54新增: if !validName(name) || strings.Contains(name, ":") {
55新增: return "", errors.New("剪贴板文件名称无效")
56新增: }
57新增: root, err := os.MkdirTemp("", "cage-clipboard-")
58新增: if err != nil {
59新增: return "", err
60新增: }
61新增: defer func() {
62新增: if err != nil {
63新增: _ = os.RemoveAll(root)
64新增: }
65新增: }()
66新增: path = filepath.Join(root, name)
67新增: file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
68新增: if err != nil {
69新增: return "", err
70新增: }
71新增: count, writeErr := io.Copy(file, io.LimitReader(input, FileLimit+1))
72新增: if count > FileLimit {
73新增: writeErr = errors.New("每个文件不能超过 2 GB")
74新增: }
75新增: if writeErr == nil {
76新增: writeErr = file.Sync()
77新增: }
78新增: if err = errors.Join(writeErr, file.Close()); err != nil {
79新增: return "", err
80新增: }
81新增: return path, nil
82新增:}
83新增:
84新增:func validName(name string) bool {
85新增: return name != "" && len(name) <= 255 && name != "." && name != ".." && !strings.ContainsAny(name, "/\\\x00") &&
86新增: !strings.ContainsFunc(name, func(r rune) bool { return r < 32 || r == 127 })
87新增:}
88新增:
89新增:func Write(output io.Writer, paths []string) error {
90新增: if len(paths) == 0 || len(paths) > SelectionLimit {
91新增: return errors.New("请选择 1 至 100 个文件或文件夹")
92新增: }
93新增: writer := tar.NewWriter(output)
94新增: names := map[string]bool{}
95新增: for _, selected := range paths {
96新增: name := filepath.Base(selected)
97新增: if !filepath.IsAbs(selected) || !validName(name) || names[name] {
98新增: return errors.New("剪贴板文件名称无效或重复")
99新增: }
100新增: names[name] = true
101新增: err := filepath.Walk(selected, func(path string, info os.FileInfo, err error) error {
102新增: if err != nil {
103新增: return errors.New("无法读取所选剪贴板文件")
104新增: }
105新增: if !(info.Mode().IsRegular() || info.IsDir()) || info.Size() > FileLimit {
106新增: return errors.New("剪贴板支持普通文件和文件夹,每个文件最多 2 GB")
107新增: }
108新增: relative, err := filepath.Rel(filepath.Dir(selected), path)
109新增: if err != nil {
110新增: return err
111新增: }
112新增: header, err := tar.FileInfoHeader(info, "")
113新增: if err != nil {
114新增: return err
115新增: }
116新增: header.Name = filepath.ToSlash(relative)
117新增: if err := writer.WriteHeader(header); err != nil {
118新增: return err
119新增: }
120新增: if !info.Mode().IsRegular() {
121新增: return nil
122新增: }
123新增: file, err := os.Open(path)
124新增: if err != nil {
125新增: return errors.New("无法读取所选剪贴板文件")
126新增: }
127新增: defer file.Close()
128新增: after, err := file.Stat()
129新增: if err != nil || !os.SameFile(info, after) || after.Size() != info.Size() {
130新增: return errors.New("文件已变化,请重新复制")
131新增: }
132新增: _, err = io.CopyN(writer, file, info.Size())
133新增: return err
134新增: })
135新增: if err != nil {
136新增: return err
137新增: }
138新增: }
139新增: return writer.Close()
140新增:}
141新增:
142新增:func Read(input io.Reader) (paths []string, err error) {
143新增: root, err := os.MkdirTemp("", "cage-clipboard-")
144新增: if err != nil {
145新增: return nil, err
146新增: }
147新增: defer func() {
148新增: if err != nil {
149新增: _ = os.RemoveAll(root)
150新增: }
151新增: }()
152新增: reader := tar.NewReader(input)
153新增: names := map[string]bool{}
154新增: for {
155新增: header, readErr := reader.Next()
156新增: if readErr == io.EOF {
157新增: break
158新增: }
159新增: if readErr != nil {
160新增: return nil, readErr
161新增: }
162新增: name := strings.TrimSuffix(header.Name, "/")
163新增: parts := strings.Split(name, "/")
164新增: if !filepath.IsLocal(filepath.FromSlash(name)) || header.Size < 0 || header.Size > FileLimit {
165新增: return nil, errors.New("剪贴板文件位置或大小无效")
166新增: }
167新增: for _, part := range parts {
168新增: if !validName(part) || strings.Contains(part, ":") {
169新增: return nil, errors.New("剪贴板文件名称无效")
170新增: }
171新增: }
172新增: if !names[parts[0]] {
173新增: names[parts[0]] = true
174新增: paths = append(paths, filepath.Join(root, parts[0]))
175新增: if len(paths) > SelectionLimit {
176新增: return nil, errors.New("剪贴板文件数量超过 100 个")
177新增: }
178新增: }
179新增: destination := filepath.Join(root, filepath.FromSlash(name))
180新增: if err = os.MkdirAll(filepath.Dir(destination), 0700); err != nil {
181新增: return nil, err
182新增: }
183新增: switch header.Typeflag {
184新增: case tar.TypeDir:
185新增: if err = os.MkdirAll(destination, 0700); err != nil {
186新增: return nil, err
187新增: }
188新增: case tar.TypeReg, tar.TypeRegA:
189新增: file, createErr := os.OpenFile(destination, os.O_WRONLY|os.O_CREATE|os.O_EXCL, os.FileMode(header.Mode)&0700|0600)
190新增: if createErr != nil {
191新增: return nil, createErr
192新增: }
193新增: _, copyErr := io.CopyN(file, reader, header.Size)
194新增: closeErr := file.Close()
195新增: if copyErr != nil || closeErr != nil {
196新增: return nil, errors.Join(copyErr, closeErr)
197新增: }
198新增: default:
199新增: return nil, errors.New("剪贴板不支持链接或特殊文件")
200新增: }
201新增: }
202新增: if len(paths) == 0 {
203新增: return nil, errors.New("剪贴板文件为空")
204新增: }
205新增: return paths, nil
206新增:}
207新增:
208新增:func Copy(paths []string) ([]string, error) {
209新增: reader, writer := io.Pipe()
210新增: defer reader.Close()
211新增: done := make(chan error, 1)
212新增: go func() { err := Write(writer, paths); writer.CloseWithError(err); done <- err }()
213新增: copied, err := Read(reader)
214新增: reader.Close()
215新增: if writeErr := <-done; writeErr != nil {
216新增: if len(copied) > 0 {
217新增: _ = os.RemoveAll(filepath.Dir(copied[0]))
218新增: }
219新增: return nil, writeErr
220新增: }
221新增: return copied, err
222新增:}
新增internal/clipboardfiles/ownership.go+230 −0看文件
@@ -0,0 +1,230 @@
1新增:package clipboardfiles
2新增:
3新增:import (
4新增: "crypto/rand"
5新增: "encoding/hex"
6新增: "encoding/json"
7新增: "errors"
8新增: "os"
9新增: "path/filepath"
10新增: "strings"
11新增:
12新增: "github.com/sylvinus/agent-vm/internal/host"
13新增:)
14新增:
15新增:// CachedSelection records a directory created by a successful receive or copy.
16新增:// The identifier is private to the native clipboard owner.
17新增:type CachedSelection struct {
18新增: ID string `json:"cache_id"`
19新增: Paths []string `json:"paths"`
20新增:}
21新增:
22新增:type cacheRecord struct {
23新增: CachedSelection
24新增: Directory string `json:"directory"`
25新增: Marker string `json:"marker"`
26新增: Owner int `json:"owner"`
27新增: Published bool `json:"published"`
28新增:}
29新增:
30新增:type CacheStore struct{ Directory string }
31新增:
32新增:type CacheRequest struct {
33新增: Action string `json:"action"`
34新增: ID string `json:"cache_id,omitempty"`
35新增:}
36新增:
37新增:func (store CacheStore) Control(request CacheRequest) (map[string]any, error) {
38新增: if request.Action == "list" {
39新增: selections, err := store.List()
40新增: return map[string]any{"selections": selections}, err
41新增: }
42新增: var err error
43新增: switch request.Action {
44新增: case "publish":
45新增: err = store.Publish(request.ID)
46新增: case "release":
47新增: err = store.Release(request.ID)
48新增: default:
49新增: err = errors.New("invalid clipboard cache operation")
50新增: }
51新增: return map[string]any{"ok": err == nil}, err
52新增:}
53新增:
54新增:func (store CacheStore) recordPath(id string) (string, error) {
55新增: if decoded, err := hex.DecodeString(id); err != nil || len(decoded) != 16 {
56新增: return "", errors.New("invalid clipboard cache identity")
57新增: }
58新增: return filepath.Join(store.Directory, id+".json"), nil
59新增:}
60新增:
61新增:// Register takes ownership only of a directory just returned by Read, Copy,
62新增:// Save or LinkCachedFiles. Existing user selections never enter this method.
63新增:func (store CacheStore) Register(paths []string) (CachedSelection, error) {
64新增: var empty CachedSelection
65新增: if len(paths) == 0 || len(paths) > SelectionLimit {
66新增: return empty, errors.New("invalid clipboard cache selection")
67新增: }
68新增: directory := filepath.Dir(paths[0])
69新增: for _, path := range paths {
70新增: if !filepath.IsAbs(path) || filepath.Clean(path) != path || filepath.Dir(path) != directory {
71新增: return empty, errors.New("invalid clipboard cache directory")
72新增: }
73新增: }
74新增: if err := host.EnsurePrivateDir(store.Directory); err != nil {
75新增: return empty, err
76新增: }
77新增: var token [16]byte
78新增: if _, err := rand.Read(token[:]); err != nil {
79新增: return empty, err
80新增: }
81新增: selection := CachedSelection{ID: hex.EncodeToString(token[:]), Paths: append([]string(nil), paths...)}
82新增: marker, err := os.CreateTemp(directory, ".cage-clipboard-owner-")
83新增: if err != nil {
84新增: return empty, err
85新增: }
86新增: _, writeErr := marker.WriteString(selection.ID)
87新增: err = errors.Join(writeErr, marker.Close())
88新增: if err != nil {
89新增: _ = os.Remove(marker.Name())
90新增: return empty, err
91新增: }
92新增: record := cacheRecord{CachedSelection: selection, Directory: directory, Marker: filepath.Base(marker.Name()), Owner: os.Getppid()}
93新增: if err := store.save(record); err != nil {
94新增: _ = os.Remove(marker.Name())
95新增: return empty, err
96新增: }
97新增: return selection, nil
98新增:}
99新增:
100新增:func (store CacheStore) save(record cacheRecord) error {
101新增: path, err := store.recordPath(record.ID)
102新增: if err != nil {
103新增: return err
104新增: }
105新增: file, err := os.CreateTemp(store.Directory, ".clipboard-record-")
106新增: if err != nil {
107新增: return err
108新增: }
109新增: defer os.Remove(file.Name())
110新增: if err := json.NewEncoder(file).Encode(record); err != nil {
111新增: _ = file.Close()
112新增: return err
113新增: }
114新增: if err := file.Close(); err != nil {
115新增: return err
116新增: }
117新增: return os.Rename(file.Name(), path)
118新增:}
119新增:
120新增:func (store CacheStore) load(id string) (cacheRecord, error) {
121新增: var record cacheRecord
122新增: path, err := store.recordPath(id)
123新增: if err != nil {
124新增: return record, err
125新增: }
126新增: data, err := os.ReadFile(path)
127新增: if err != nil {
128新增: return record, err
129新增: }
130新增: if json.Unmarshal(data, &record) != nil || record.ID != id || len(record.Paths) == 0 ||
131新增: !filepath.IsAbs(record.Directory) || filepath.Clean(record.Directory) != record.Directory ||
132新增: !validName(record.Marker) || record.Owner < 1 {
133新增: return record, errors.New("invalid clipboard cache record")
134新增: }
135新增: for _, path := range record.Paths {
136新增: if filepath.Dir(path) != record.Directory || filepath.Clean(path) != path {
137新增: return record, errors.New("invalid clipboard cache paths")
138新增: }
139新增: }
140新增: return record, nil
141新增:}
142新增:
143新增:func (store CacheStore) Publish(id string) error {
144新增: record, err := store.load(id)
145新增: if err != nil {
146新增: return err
147新增: }
148新增: record.Published = true
149新增: return store.save(record)
150新增:}
151新增:
152新增:// List recovers published copies and abandoned receives from their creation
153新增:// records. A live native owner retains admission for its unpublished transfers.
154新增:func (store CacheStore) List() ([]CachedSelection, error) {
155新增: entries, err := os.ReadDir(store.Directory)
156新增: if errors.Is(err, os.ErrNotExist) {
157新增: return []CachedSelection{}, nil
158新增: }
159新增: if err != nil {
160新增: return nil, err
161新增: }
162新增: selections := []CachedSelection{}
163新增: for _, entry := range entries {
164新增: if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {
165新增: continue
166新增: }
167新增: record, err := store.load(strings.TrimSuffix(entry.Name(), ".json"))
168新增: if err != nil {
169新增: return nil, err
170新增: }
171新增: if record.Published || !cacheOwnerAlive(record.Owner) {
172新增: selections = append(selections, record.CachedSelection)
173新增: }
174新增: }
175新增: return selections, nil
176新增:}
177新增:
178新增:// Release runs after the native owner has checked the current OS selection and
179新增:// its in-flight readers. A Windows sharing violation keeps the receipt for retry.
180新增:func (store CacheStore) Release(id string) error {
181新增: record, err := store.load(id)
182新增: if errors.Is(err, os.ErrNotExist) {
183新增: return nil
184新增: }
185新增: if err != nil {
186新增: return err
187新增: }
188新增: path, _ := store.recordPath(id)
189新增: root, err := os.OpenRoot(record.Directory)
190新增: if errors.Is(err, os.ErrNotExist) {
191新增: return os.Remove(path)
192新增: }
193新增: if err != nil {
194新增: return err
195新增: }
196新增: defer root.Close()
197新增: marker, err := root.ReadFile(record.Marker)
198新增: if err != nil || string(marker) != id {
199新增: return errors.New("clipboard cache creation record no longer matches")
200新增: }
201新增: directory, err := root.Open(".")
202新增: if err != nil {
203新增: return err
204新增: }
205新增: entries, readErr := directory.ReadDir(-1)
206新增: err = errors.Join(readErr, directory.Close())
207新增: if err != nil {
208新增: return err
209新增: }
210新增: for _, entry := range entries {
211新增: if entry.Name() != record.Marker {
212新增: if err := root.RemoveAll(entry.Name()); err != nil {
213新增: return err
214新增: }
215新增: }
216新增: }
217新增: if err := root.Remove(record.Marker); err != nil {
218新增: return err
219新增: }
220新增: if err := os.Remove(record.Directory); err != nil {
221新增: // A busy directory must retain its proof of ownership for a later retry.
222新增: return errors.Join(err, root.WriteFile(record.Marker, []byte(id), 0600))
223新增: }
224新增: return os.Remove(path)
225新增:}
226新增:
227新增:func UserCacheStore() (CacheStore, error) {
228新增: directory, err := os.UserCacheDir()
229新增: return CacheStore{Directory: filepath.Join(directory, "cage", "clipboard-ownership")}, err
230新增:}
新增internal/clipboardfiles/ownership_test.go+101 −0看文件
@@ -0,0 +1,101 @@
1新增:package clipboardfiles
2新增:
3新增:import (
4新增: "os"
5新增: "path/filepath"
6新增: "strings"
7新增: "testing"
8新增:)
9新增:
10新增:func cacheFixture(t *testing.T) (CacheStore, CachedSelection) {
11新增: t.Helper()
12新增: directory := t.TempDir()
13新增: created, err := os.MkdirTemp(directory, "created-")
14新增: if err != nil {
15新增: t.Fatal(err)
16新增: }
17新增: path := filepath.Join(created, "fixture.txt")
18新增: if err := os.WriteFile(path, []byte("complete copied bytes"), 0600); err != nil {
19新增: t.Fatal(err)
20新增: }
21新增: store := CacheStore{Directory: filepath.Join(directory, "records")}
22新增: selection, err := store.Register([]string{path})
23新增: if err != nil {
24新增: t.Fatal(err)
25新增: }
26新增: return store, selection
27新增:}
28新增:
29新增:func TestCacheReleaseUsesItsCreationRecord(t *testing.T) {
30新增: store, selection := cacheFixture(t)
31新增: unrelated := filepath.Join(t.TempDir(), "cage-clipboard-unrelated")
32新增: if err := os.Mkdir(unrelated, 0700); err != nil {
33新增: t.Fatal(err)
34新增: }
35新增: if err := store.Release(selection.ID); err != nil {
36新增: t.Fatal(err)
37新增: }
38新增: if _, err := os.Stat(filepath.Dir(selection.Paths[0])); !os.IsNotExist(err) {
39新增: t.Fatal("owned copy remained")
40新增: }
41新增: if _, err := os.Stat(unrelated); err != nil {
42新增: t.Fatal("unrelated directory changed")
43新增: }
44新增: if err := store.Release(selection.ID); err != nil {
45新增: t.Fatal("release was not idempotent", err)
46新增: }
47新增:}
48新增:
49新增:func TestCacheReleaseRejectsChangedCreationMarker(t *testing.T) {
50新增: store, selection := cacheFixture(t)
51新增: record, err := store.load(selection.ID)
52新增: if err != nil {
53新增: t.Fatal(err)
54新增: }
55新增: if err := os.WriteFile(filepath.Join(record.Directory, record.Marker), []byte("changed"), 0600); err != nil {
56新增: t.Fatal(err)
57新增: }
58新增: if err := store.Release(selection.ID); err == nil {
59新增: t.Fatal("changed directory ownership was accepted")
60新增: }
61新增: if data, err := os.ReadFile(selection.Paths[0]); err != nil || string(data) != "complete copied bytes" {
62新增: t.Fatal("unverified files were removed")
63新增: }
64新增:}
65新增:
66新增:func TestCacheRecoveryKeepsUnpublishedLiveTransfers(t *testing.T) {
67新增: store, selection := cacheFixture(t)
68新增: listed, err := store.List()
69新增: if err != nil || len(listed) != 0 {
70新增: t.Fatal("an active unpublished transfer was collected", err)
71新增: }
72新增: if err := store.Publish(selection.ID); err != nil {
73新增: t.Fatal(err)
74新增: }
75新增: listed, err = store.List()
76新增: if err != nil || len(listed) != 1 || listed[0].ID != selection.ID {
77新增: t.Fatal("published ownership could not be restored", err)
78新增: }
79新增: record, _ := store.load(selection.ID)
80新增: record.Published = false
81新增: record.Owner = 2147483647
82新增: if err := store.save(record); err != nil {
83新增: t.Fatal(err)
84新增: }
85新增: listed, err = store.List()
86新增: if err != nil || len(listed) != 1 {
87新增: t.Fatal("abandoned receive ownership was lost", err)
88新增: }
89新增:}
90新增:
91新增:func TestCacheRejectsForeignOrMalformedIdentifiers(t *testing.T) {
92新增: store, selection := cacheFixture(t)
93新增: for _, id := range []string{"../outside", "", strings.Repeat("g", 32)} {
94新增: if err := store.Release(id); err == nil {
95新增: t.Fatal("invalid cache identifier admitted")
96新增: }
97新增: }
98新增: if _, err := os.Stat(selection.Paths[0]); err != nil {
99新增: t.Fatal(err)
100新增: }
101新增:}
新增internal/clipboardfiles/ownership_unix.go+10 −0看文件
@@ -0,0 +1,10 @@
1新增://go:build !windows
2新增:
3新增:package clipboardfiles
4新增:
5新增:import "syscall"
6新增:
7新增:func cacheOwnerAlive(pid int) bool {
8新增: err := syscall.Kill(pid, 0)
9新增: return err == nil || err == syscall.EPERM
10新增:}
新增internal/clipboardfiles/ownership_unix_test.go+50 −0看文件
@@ -0,0 +1,50 @@
1新增://go:build !windows
2新增:
3新增:package clipboardfiles
4新增:
5新增:import (
6新增: "io"
7新增: "os"
8新增: "path/filepath"
9新增: "testing"
10新增:)
11新增:
12新增:func TestCacheReleasePreservesAnAlreadyOpenExternalReader(t *testing.T) {
13新增: store, selection := cacheFixture(t)
14新增: reader, err := os.Open(selection.Paths[0])
15新增: if err != nil {
16新增: t.Fatal(err)
17新增: }
18新增: defer reader.Close()
19新增: if err := store.Release(selection.ID); err != nil {
20新增: t.Fatal(err)
21新增: }
22新增: data, err := io.ReadAll(reader)
23新增: if err != nil || string(data) != "complete copied bytes" {
24新增: t.Fatal("the open external reader lost its bytes", err)
25新增: }
26新增: if _, err := os.Open(selection.Paths[0]); !os.IsNotExist(err) {
27新增: t.Fatal("a retired path remained available to a new reader")
28新增: }
29新增:}
30新增:
31新增:func TestCacheReleaseRetainsMarkerAfterDirectoryRemovalFailure(t *testing.T) {
32新增: if os.Geteuid() == 0 {
33新增: t.Skip("root can remove the protected test directory")
34新增: }
35新增: store, selection := cacheFixture(t)
36新增: parent := filepath.Dir(filepath.Dir(selection.Paths[0]))
37新增: if err := os.Chmod(parent, 0500); err != nil {
38新增: t.Fatal(err)
39新增: }
40新增: defer os.Chmod(parent, 0700)
41新增: if err := store.Release(selection.ID); err == nil {
42新增: t.Fatal("a protected directory was removed")
43新增: }
44新增: if err := os.Chmod(parent, 0700); err != nil {
45新增: t.Fatal(err)
46新增: }
47新增: if err := store.Release(selection.ID); err != nil {
48新增: t.Fatal("the failed removal lost its creation proof", err)
49新增: }
50新增:}
新增internal/clipboardfiles/ownership_windows.go+13 −0看文件
@@ -0,0 +1,13 @@
1新增:package clipboardfiles
2新增:
3新增:import "golang.org/x/sys/windows"
4新增:
5新增:func cacheOwnerAlive(pid int) bool {
6新增: handle, err := windows.OpenProcess(windows.SYNCHRONIZE, false, uint32(pid))
7新增: if err != nil {
8新增: return err == windows.ERROR_ACCESS_DENIED
9新增: }
10新增: defer windows.CloseHandle(handle)
11新增: status, err := windows.WaitForSingleObject(handle, 0)
12新增: return err != nil || status == uint32(windows.WAIT_TIMEOUT)
13新增:}
新增internal/clipboardfiles/ownership_windows_test.go+43 −0看文件
@@ -0,0 +1,43 @@
1新增:package clipboardfiles
2新增:
3新增:import (
4新增: "os"
5新增: "testing"
6新增:
7新增: "golang.org/x/sys/windows"
8新增:)
9新增:
10新增:func TestCacheReleaseRetriesAfterExternalWindowsReaderCloses(t *testing.T) {
11新增: store, selection := cacheFixture(t)
12新增: name, err := windows.UTF16PtrFromString(selection.Paths[0])
13新增: if err != nil {
14新增: t.Fatal(err)
15新增: }
16新增: reader, err := windows.CreateFile(name, windows.GENERIC_READ, windows.FILE_SHARE_READ, nil, windows.OPEN_EXISTING, 0, 0)
17新增: if err != nil {
18新增: t.Fatal(err)
19新增: }
20新增: defer func() {
21新增: if reader != 0 {
22新增: windows.CloseHandle(reader)
23新增: }
24新增: }()
25新增: if err := store.Release(selection.ID); err == nil {
26新增: t.Fatal("a file opened without delete sharing was removed")
27新增: }
28新增: buffer := make([]byte, 64)
29新增: var count uint32
30新增: if err := windows.ReadFile(reader, buffer, &count, nil); err != nil || string(buffer[:count]) != "complete copied bytes" {
31新增: t.Fatal("the external reader lost its file", err)
32新增: }
33新增: if err := windows.CloseHandle(reader); err != nil {
34新增: t.Fatal(err)
35新增: }
36新增: reader = 0
37新增: if err := store.Release(selection.ID); err != nil {
38新增: t.Fatal("release could not retry", err)
39新增: }
40新增: if _, err := os.Stat(selection.Paths[0]); !os.IsNotExist(err) {
41新增: t.Fatal("released cache remained")
42新增: }
43新增:}
新增internal/guestos/components.go+224 −0看文件
@@ -0,0 +1,224 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "bytes"
5新增: "crypto/sha256"
6新增: "encoding/hex"
7新增: "encoding/json"
8新增: "errors"
9新增: "fmt"
10新增: "io"
11新增: "io/fs"
12新增: "os"
13新增: "path"
14新增: "path/filepath"
15新增: "sort"
16新增: "strings"
17新增:
18新增: "github.com/sylvinus/agent-vm/internal/cage"
19新增: "github.com/sylvinus/agent-vm/internal/version"
20新增:)
21新增:
22新增:const MacOSBrowserTools = "/usr/local/libexec/cage-workbench-browser-4.145.0-pw1.65.0"
23新增:const MacOSCLIRuntime = "/usr/local/libexec/cage-cli-runtime-2.1.311-py3.13.18-git2.56.0"
24新增:
25新增:type NativeComponentFile struct {
26新增: Source string `json:"source"`
27新增: Target string `json:"target,omitempty"`
28新增: SHA256 string `json:"sha256"`
29新增: InstalledSHA256 string `json:"installed_sha256"`
30新增:}
31新增:
32新增:type NativeComponentManifest struct {
33新增: cage.GuestManifest
34新增: System string `json:"system"`
35新增: Files []NativeComponentFile `json:"files"`
36新增: Tools map[string]string `json:"tools"`
37新增:}
38新增:
39新增:// The installed application bundle is the required component source. Walking
40新增:// its actual contents includes newly added helper resources and browser modules.
41新增:func RequiredNativeComponents(kit, system string) (NativeComponentManifest, error) {
42新增: manifest := NativeComponentManifest{GuestManifest: cage.GuestManifest{Protocol: 1, AppVersion: version.Version}, System: system}
43新增: if system != MacOS && system != Windows11 {
44新增: return manifest, errors.New("原生客机系统无效")
45新增: }
46新增: essential := []string{"payload/Cage.GuestClipboard.exe", "payload/cage-guest-files.exe", "payload/cage-guest-boot.exe", "payload/Cage.HyperVManager.exe", "payload/windows-browser.mjs"}
47新增: if system == MacOS {
48新增: essential = []string{"Cage Guest Window.app/Contents/MacOS/CageGuestWindow", "Cage Guest Clipboard.app/Contents/MacOS/CageGuestClipboard", "project/cage-sshfs", "project/cage-macos-terminal", "native-browser/macos-native-browser.mjs", "native-browser/macos-browser-service.mjs", "register-macos-browser.sh", "macos-cli.py", "cli_channel.py"}
49新增: }
50新增: for _, relative := range essential {
51新增: info, err := os.Lstat(filepath.Join(kit, filepath.FromSlash(relative)))
52新增: if err != nil || !info.Mode().IsRegular() {
53新增: return manifest, fmt.Errorf("原生组件包缺少 %s", relative)
54新增: }
55新增: }
56新增: err := filepath.WalkDir(kit, func(filename string, entry fs.DirEntry, walkErr error) error {
57新增: if walkErr != nil {
58新增: return walkErr
59新增: }
60新增: if entry.IsDir() {
61新增: return nil
62新增: }
63新增: if entry.Type()&os.ModeSymlink != 0 {
64新增: return errors.New("原生组件目录不能包含文件链接")
65新增: }
66新增: info, err := entry.Info()
67新增: if err != nil {
68新增: return err
69新增: }
70新增: if !info.Mode().IsRegular() {
71新增: return errors.New("原生组件目录包含特殊文件")
72新增: }
73新增: relative, err := filepath.Rel(kit, filename)
74新增: if err != nil {
75新增: return err
76新增: }
77新增: relative = filepath.ToSlash(relative)
78新增: if relative == "native-components.json" {
79新增: return nil
80新增: }
81新增: file, err := os.Open(filename)
82新增: if err != nil {
83新增: return err
84新增: }
85新增: hash := sha256.New()
86新增: _, readErr := io.Copy(hash, file)
87新增: if err = errors.Join(readErr, file.Close()); err != nil {
88新增: return err
89新增: }
90新增: digest := hex.EncodeToString(hash.Sum(nil))
91新增: target := nativeComponentTarget(relative, system)
92新增: installed := digest
93新增: if system == MacOS && relative == "claude-account.py" {
94新增: data, err := os.ReadFile(filename)
95新增: if err != nil {
96新增: return err
97新增: }
98新增: _, body, found := bytes.Cut(data, []byte("\n"))
99新增: if !found {
100新增: return errors.New("账号组件缺少程序正文")
101新增: }
102新增: rewritten := sha256.Sum256(append([]byte("#!"+MacOSCLIRuntime+"/bin/python3 -I\n"), body...))
103新增: installed = hex.EncodeToString(rewritten[:])
104新增: }
105新增: manifest.Files = append(manifest.Files, NativeComponentFile{Source: relative, Target: target, SHA256: digest, InstalledSHA256: installed})
106新增: if system == Windows11 && relative == "payload/Cage.GuestClipboard.exe" {
107新增: manifest.Files = append(manifest.Files, NativeComponentFile{Source: relative, Target: "network/Cage.GuestNetwork.exe", SHA256: digest, InstalledSHA256: installed})
108新增: }
109新增: return nil
110新增: })
111新增: if err != nil {
112新增: return manifest, err
113新增: }
114新增: if len(manifest.Files) == 0 {
115新增: return manifest, errors.New("此应用缺少原生客机组件")
116新增: }
117新增: sort.Slice(manifest.Files, func(i, j int) bool {
118新增: if manifest.Files[i].Source != manifest.Files[j].Source {
119新增: return manifest.Files[i].Source < manifest.Files[j].Source
120新增: }
121新增: return manifest.Files[i].Target < manifest.Files[j].Target
122新增: })
123新增: digest := sha256.New()
124新增: fmt.Fprintf(digest, "cage-native-components-1\x00%s\x00", system)
125新增: for _, file := range manifest.Files {
126新增: fmt.Fprintf(digest, "%s\x00%s\x00%s\x00%s\x00", file.Source, file.Target, file.SHA256, file.InstalledSHA256)
127新增: }
128新增: manifest.Revision = hex.EncodeToString(digest.Sum(nil))
129新增: manifest.Tools = map[string]string{"chromium": "系统维护的 Chrome / Edge", "code_server": "261c84cb1eddf11235f9e2c921425e9663fbe556"}
130新增: if system == MacOS {
131新增: manifest.Tools = map[string]string{"chromium": "Google Chrome 稳定版", "code_server": "4.145.0", "claude": "2.1.311", "node": "24.22.2", "python": "3.13.18", "git": "2.56.0"}
132新增: } else {
133新增: var dependencies map[string]struct {
134新增: Version string `json:"version"`
135新增: }
136新增: if data, err := os.ReadFile(filepath.Join(kit, "payload", "cli-dependencies.json")); err != nil {
137新增: return manifest, err
138新增: } else if err = json.Unmarshal(data, &dependencies); err != nil {
139新增: return manifest, err
140新增: }
141新增: for _, name := range []string{"claude", "python", "git"} {
142新增: manifest.Tools[name] = dependencies[name].Version
143新增: }
144新增: manifest.Tools["node"] = "24.22.2"
145新增: }
146新增: return manifest, manifest.Validate()
147新增:}
148新增:
149新增:func nativeComponentTarget(source, system string) string {
150新增: if system == Windows11 {
151新增: if !strings.HasPrefix(source, "payload/") {
152新增: return ""
153新增: }
154新增: name := strings.TrimPrefix(source, "payload/")
155新增: if name == "Cage.HyperVManager.exe" || name == "windows-workbench-packages.json" {
156新增: return ""
157新增: }
158新增: return "bridge/" + name
159新增: }
160新增: switch {
161新增: case strings.HasPrefix(source, "Cage ") && strings.Contains(source, ".app/"):
162新增: return "/Applications/" + source
163新增: case strings.HasPrefix(source, "project/CageProjectAccess.app/"):
164新增: return "/Applications/" + strings.TrimPrefix(source, "project/")
165新增: case strings.HasPrefix(source, "native-browser/"):
166新增: return MacOSBrowserTools + "/controller/" + strings.TrimPrefix(source, "native-browser/")
167新增: }
168新增: targets := map[string]string{
169新增: "project/cage-sshfs": "/usr/local/libexec/cage-sshfs",
170新增: "project/cage-macos-terminal": "/usr/local/libexec/cage-macos-terminal",
171新增: "cage-finish-initial-setup": "/usr/local/libexec/cage-finish-initial-setup",
172新增: "cage-macos-ipv6-check": "/usr/local/libexec/cage-macos-ipv6-check",
173新增: "macos-browser.mjs": "/usr/local/libexec/cage-macos-browser.mjs",
174新增: "cage-macos-editor": "/usr/local/libexec/cage-macos-editor",
175新增: "register-macos-claude-window.sh": "/usr/local/libexec/cage-register-claude-window",
176新增: "register-macos-clipboard.sh": "/usr/local/libexec/cage-register-clipboard",
177新增: "register-macos-browser.sh": "/usr/local/libexec/cage-register-browser",
178新增: "macos-cli.py": "/usr/local/libexec/cage-cli/macos-cli.py",
179新增: "cli_channel.py": "/usr/local/libexec/cage-cli/cli_channel.py",
180新增: "cli_channel.resume.md": "/usr/local/libexec/cage-cli/cli_channel.resume.md",
181新增: "claude_account_resume.md": "/usr/local/libexec/cage-cli/cli_channel.account-resume.md",
182新增: "claude-account.py": "/usr/local/libexec/cage-cli/bin/cage-claude-account",
183新增: }
184新增: return targets[source]
185新增:}
186新增:
187新增:func (m NativeComponentManifest) Validate() error {
188新增: if m.Protocol != 1 || (m.System != MacOS && m.System != Windows11) || len(m.Revision) != 64 || len(m.Files) == 0 || len(m.Files) > 10000 {
189新增: return errors.New("原生组件清单无效")
190新增: }
191新增: if _, err := hex.DecodeString(m.Revision); err != nil {
192新增: return errors.New("原生组件版本摘要无效")
193新增: }
194新增: seen := map[string]bool{}
195新增: for _, file := range m.Files {
196新增: key := file.Source + "\x00" + file.Target
197新增: if !fs.ValidPath(file.Source) || strings.ContainsAny(file.Source+file.Target, "\x00\r\n") || seen[key] || len(file.SHA256) != 64 || len(file.InstalledSHA256) != 64 {
198新增: return errors.New("原生组件文件记录无效")
199新增: }
200新增: if _, err := hex.DecodeString(file.SHA256 + file.InstalledSHA256); err != nil {
201新增: return errors.New("原生组件摘要无效")
202新增: }
203新增: if file.Target != "" && (path.Clean(file.Target) != file.Target || strings.Contains(file.Target, "\\")) {
204新增: return errors.New("原生组件安装位置无效")
205新增: }
206新增: if file.Target != "" && seen["\x00"+file.Target] {
207新增: return errors.New("原生组件安装位置重复")
208新增: }
209新增: if file.Target != "" && m.System == MacOS && !strings.HasPrefix(file.Target, "/Applications/Cage") && !strings.HasPrefix(file.Target, "/usr/local/libexec/cage-") {
210新增: return errors.New("macOS 组件安装位置无效")
211新增: }
212新增: if file.Target != "" && m.System == Windows11 && !strings.HasPrefix(file.Target, "bridge/") && !strings.HasPrefix(file.Target, "network/") {
213新增: return errors.New("Windows 组件安装位置无效")
214新增: }
215新增: if m.System == Windows11 && strings.ContainsAny(file.Source+file.Target, ":\\") {
216新增: return errors.New("Windows 组件文件名无效")
217新增: }
218新增: seen[key] = true
219新增: if file.Target != "" {
220新增: seen["\x00"+file.Target] = true
221新增: }
222新增: }
223新增: return nil
224新增:}
新增internal/guestos/components_test.go+96 −0看文件
@@ -0,0 +1,96 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "crypto/sha256"
5新增: "encoding/hex"
6新增: "os"
7新增: "path/filepath"
8新增: "testing"
9新增:)
10新增:
11新增:func nativeManifestKit(t *testing.T, system string) string {
12新增: t.Helper()
13新增: kit := t.TempDir()
14新增: names := []string{"payload/Cage.GuestClipboard.exe", "payload/cage-guest-files.exe", "payload/cage-guest-boot.exe", "payload/Cage.HyperVManager.exe", "payload/windows-browser.mjs", "payload/cli-dependencies.json"}
15新增: if system == MacOS {
16新增: names = []string{"Cage Guest Window.app/Contents/MacOS/CageGuestWindow", "Cage Guest Clipboard.app/Contents/MacOS/CageGuestClipboard", "project/cage-sshfs", "project/cage-macos-terminal", "native-browser/macos-native-browser.mjs", "native-browser/macos-browser-service.mjs", "register-macos-browser.sh", "macos-cli.py", "cli_channel.py", "claude-account.py"}
17新增: }
18新增: for _, name := range names {
19新增: filename := filepath.Join(kit, filepath.FromSlash(name))
20新增: if err := os.MkdirAll(filepath.Dir(filename), 0700); err != nil {
21新增: t.Fatal(err)
22新增: }
23新增: data := []byte("#!fixture\n{}")
24新增: if name == "payload/cli-dependencies.json" {
25新增: data = []byte(`{"claude":{"version":"2.1.311"},"python":{"version":"3.13.18"},"git":{"version":"2.56.0"}}`)
26新增: }
27新增: if err := os.WriteFile(filename, data, 0600); err != nil {
28新增: t.Fatal(err)
29新增: }
30新增: }
31新增: return kit
32新增:}
33新增:
34新增:func TestNativeManifestTracksInstalledComponents(t *testing.T) {
35新增: for _, system := range []string{MacOS, Windows11} {
36新增: t.Run(system, func(t *testing.T) {
37新增: kit := nativeManifestKit(t, system)
38新增: first, err := RequiredNativeComponents(kit, system)
39新增: if err != nil {
40新增: t.Fatal(err)
41新增: }
42新增: again, err := RequiredNativeComponents(kit, system)
43新增: if err != nil || first.Revision != again.Revision {
44新增: t.Fatalf("manifest is unstable: %v", err)
45新增: }
46新增: source := "payload/new-phone-browser.mjs"
47新增: if system == MacOS {
48新增: source = "native-browser/macos-phone-browser.mjs"
49新增: }
50新增: if err = os.WriteFile(filepath.Join(kit, filepath.FromSlash(source)), []byte("phone-browser"), 0600); err != nil {
51新增: t.Fatal(err)
52新增: }
53新增: next, err := RequiredNativeComponents(kit, system)
54新增: if err != nil || next.Revision == first.Revision {
55新增: t.Fatalf("new component was omitted: %v", err)
56新增: }
57新增: found, packet := false, false
58新增: for _, item := range next.Files {
59新增: if item.Source == source {
60新增: found = item.Target != "" && item.SHA256 == item.InstalledSHA256
61新增: }
62新增: if item.Target == "network/Cage.GuestNetwork.exe" {
63新增: packet = item.Source == "payload/Cage.GuestClipboard.exe"
64新增: }
65新增: if item.Source == "claude-account.py" {
66新增: expected := sha256.Sum256([]byte("#!" + MacOSCLIRuntime + "/bin/python3 -I\n{}"))
67新增: if item.InstalledSHA256 != hex.EncodeToString(expected[:]) {
68新增: t.Fatal("installed Python entry point digest differs from installer")
69新增: }
70新增: }
71新增: }
72新增: if !found || (system == Windows11 && !packet) {
73新增: t.Fatal("manifest did not include installed guest capabilities")
74新增: }
75新增: if err = os.Symlink(source, filepath.Join(kit, "unexpected-link")); err != nil {
76新增: t.Skipf("symlinks unavailable: %v", err)
77新增: }
78新增: if _, err = RequiredNativeComponents(kit, system); err == nil {
79新增: t.Fatal("linked payload was accepted")
80新增: }
81新增: })
82新增: }
83新增:}
84新增:
85新增:func TestNativeManifestRejectsEscapedTargets(t *testing.T) {
86新增: manifest, err := RequiredNativeComponents(nativeManifestKit(t, MacOS), MacOS)
87新增: if err != nil {
88新增: t.Fatal(err)
89新增: }
90新增: for _, target := range []string{"/usr/local/libexec/cage-cli/../../private", "/etc/passwd", "network/Cage.GuestNetwork.exe"} {
91新增: manifest.Files[0].Target = target
92新增: if manifest.Validate() == nil {
93新增: t.Fatalf("accepted target %q", target)
94新增: }
95新增: }
96新增:}
新增internal/guestos/host_source_test.go+137 −0看文件
@@ -0,0 +1,137 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "os"
5新增: "path/filepath"
6新增: "strings"
7新增: "testing"
8新增:
9新增: "github.com/google/uuid"
10新增: "github.com/sylvinus/agent-vm/internal/hostimage"
11新增:)
12新增:
13新增:func TestHostSourcePublishesOneVerifiedMediaReceipt(t *testing.T) {
14新增: profile := t.TempDir()
15新增: source := hostimage.Plan{Host: hostimage.Identity{System: Windows11, Version: "25H2", Build: "26200.9", Edition: "Professional", Language: "zh-CN", Arch: "amd64"}, Version: "25H2", Build: "26200.8", Format: "esd", URL: "http://dl.delivery.mp.microsoft.com/example.esd", Digest: "sha256:" + strings.Repeat("a", 64), Bytes: 10}
16新增: install := Installation{Version: 1, ID: uuid.New(), System: Windows11, EditorTerms: true, Source: source}
17新增: if err := SaveInstallation(profile, install); err != nil {
18新增: t.Fatal(err)
19新增: }
20新增: original, _ := os.ReadFile(filepath.Join(profile, installRecord))
21新增: ready := source
22新增: ready.Path = filepath.Join(profile, "system.esd")
23新增: ready.Modified = 123
24新增: if err := RecordPreparedMedia(profile, install.ID, ready); err != nil {
25新增: t.Fatal(err)
26新增: }
27新增: loaded, err := LoadInstallation(profile)
28新增: if err != nil || loaded.Media != ready.Path || loaded.Source != ready {
29新增: t.Fatalf("loaded: %+v %v", loaded, err)
30新增: }
31新增: if err := SaveInstallation(profile, *loaded); err != nil {
32新增: t.Fatal(err)
33新增: }
34新增: if err := RecordPreparedMedia(profile, install.ID, ready); err != nil {
35新增: t.Fatal(err)
36新增: }
37新增: after, _ := os.ReadFile(filepath.Join(profile, installRecord))
38新增: if string(original) != string(after) {
39新增: t.Fatal("changed original installation choice")
40新增: }
41新增: changed := ready
42新增: changed.Host.Edition = "Enterprise"
43新增: if err := RecordPreparedMedia(profile, install.ID, changed); err == nil {
44新增: t.Fatal("accepted another edition")
45新增: }
46新增: if err := RecordPreparedMedia(profile, uuid.New(), ready); err == nil {
47新增: t.Fatal("accepted another installation")
48新增: }
49新增: changed = ready
50新增: changed.Path = filepath.Join(profile, "other.esd")
51新增: if err := RecordPreparedMedia(profile, install.ID, changed); err == nil {
52新增: t.Fatal("replaced published media")
53新增: }
54新增:}
55新增:
56新增:func TestLegacyInstallationOmitsSource(t *testing.T) {
57新增: profile := t.TempDir()
58新增: if err := SaveInstallation(profile, Installation{Version: 1, ID: uuid.New(), System: MacOS}); err != nil {
59新增: t.Fatal(err)
60新增: }
61新增: data, _ := os.ReadFile(filepath.Join(profile, installRecord))
62新增: if strings.Contains(string(data), `"source"`) {
63新增: t.Fatal("legacy choice acquired source metadata")
64新增: }
65新增:}
66新增:
67新增:func TestWindowsCloneCleanupTracksRetainedCredential(t *testing.T) {
68新增: profile := t.TempDir()
69新增: source := hostimage.Plan{
70新增: Host: hostimage.Identity{System: Windows11, Version: "25H2", Edition: "Professional", Language: "zh-CN", Arch: "amd64"},
71新增: Version: "25H2", Build: "26200.8", Format: "esd", Path: filepath.Join(profile, "system.esd"),
72新增: }
73新增: install := Installation{Version: 1, ID: uuid.New(), System: Windows11, EditorTerms: true, Source: source}
74新增: if err := SaveInstallation(profile, install); err != nil {
75新增: t.Fatal(err)
76新增: }
77新增: path := filepath.Join(profile, "windows-setup-"+strings.ReplaceAll(install.ID.String(), "-", "")+".dpapi")
78新增: if err := os.WriteFile(path, []byte("encrypted-fixture"), 0600); err != nil {
79新增: t.Fatal(err)
80新增: }
81新增: pending, err := WindowsCloneCleanupPending(profile)
82新增: if err != nil || !pending {
83新增: t.Fatalf("retained credential bypassed cleanup: %v %v", pending, err)
84新增: }
85新增: if err := os.Remove(path); err != nil {
86新增: t.Fatal(err)
87新增: }
88新增: pending, err = WindowsCloneCleanupPending(profile)
89新增: if err != nil || pending {
90新增: t.Fatalf("completed cleanup still blocks activation: %v %v", pending, err)
91新增: }
92新增:}
93新增:
94新增:func TestLinuxCloneKeepsItsChoiceAfterBaseInstallation(t *testing.T) {
95新增: for _, name := range []string{"base-building", "base"} {
96新增: t.Run(name, func(t *testing.T) {
97新增: profile := t.TempDir()
98新增: install := Installation{
99新增: Version: 1, ID: uuid.New(), System: "ubuntu-22.04",
100新增: Source: hostimage.Plan{
101新增: Host: hostimage.Identity{System: "ubuntu-22.04", Version: "22.04", Arch: "amd64"},
102新增: Version: "22.04", Format: "qcow2", Path: filepath.Join(profile, "ubuntu.img"),
103新增: Digest: "sha256:" + strings.Repeat("a", 64),
104新增: },
105新增: }
106新增: if err := SaveInstallation(profile, install); err != nil {
107新增: t.Fatal(err)
108新增: }
109新增: disk := filepath.Join(profile, "state", "lima", name)
110新增: if err := os.MkdirAll(disk, 0700); err != nil {
111新增: t.Fatal(err)
112新增: }
113新增: unstarted, err := UnstartedInstallation(profile, install)
114新增: if err != nil || unstarted {
115新增: t.Fatalf("existing base was treated as an unstarted choice: %v %v", unstarted, err)
116新增: }
117新增: if err := ClearUnstartedInstallation(profile, install.ID); err == nil {
118新增: t.Fatal("cleared a choice that already produced a base disk")
119新增: }
120新增: if err := FinishLinuxInstallation(profile, install.ID); err == nil {
121新增: t.Fatal("finished without a durable Linux choice")
122新增: }
123新增: if pending, err := LoadInstallation(profile); err != nil || pending == nil {
124新增: t.Fatal("lost installation recovery information", err)
125新增: }
126新增: if err := hostimage.WriteLinuxTemplate(filepath.Join(profile, "state"), install.Source); err != nil {
127新增: t.Fatal(err)
128新增: }
129新增: if err := FinishLinuxInstallation(profile, install.ID); err != nil {
130新增: t.Fatal(err)
131新增: }
132新增: if _, err := os.Stat(disk); err != nil {
133新增: t.Fatal("finishing the installation affected its disk", err)
134新增: }
135新增: })
136新增: }
137新增:}
新增internal/guestos/hyperv_instance.go+23 −0看文件
@@ -0,0 +1,23 @@
1新增:package guestos
2新增:
3新增:// HyperVInspection describes only the VM explicitly requested by its caller.
4新增:// A matched VM is not automatically owned by the current Cage profile.
5新增:type HyperVInspection struct {
6新增: Inspection
7新增: VMID string `json:"vmId"`
8新增: Lookup string `json:"lookup"` // found, not-found (for this user), or unavailable
9新增: LookupDetail string `json:"lookupDetail,omitempty"`
10新增: VM *HyperVConfiguration `json:"vm,omitempty"`
11新增:}
12新增:
13新增:type HyperVConfiguration struct {
14新增: State string `json:"state"`
15新增: Generation int `json:"generation"`
16新增: DiskCount int `json:"diskCount"`
17新增: SingleLocalVHDX *bool `json:"singleLocalVhdx"` // null if local disk metadata was unreadable
18新增: DiskType string `json:"diskType,omitempty"`
19新增: SecureBoot bool `json:"secureBoot"`
20新增: SecureBootTemplate string `json:"secureBootTemplate,omitempty"`
21新增: VirtualTPM bool `json:"virtualTpm"`
22新增: NetworkAdapterCount int `json:"networkAdapterCount"`
23新增:}
新增internal/guestos/hyperv_instance.ps1+49 −0看文件
@@ -0,0 +1,49 @@
1新增:$ErrorActionPreference = 'Stop'
2新增:$ProgressPreference = 'SilentlyContinue'
3新增:$WarningPreference = 'SilentlyContinue'
4新增:[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
5新增:# An exact CIM query can return zero matches without conflating a failed or
6新增:# unauthorized management request with a nonexistent VM.
7新增:$systems = @(Get-CimInstance -Namespace root/virtualization/v2 -ClassName Msvm_ComputerSystem -Filter "Name='$targetId'")
8新增:if ($systems.Count -eq 0) { Write-Output 'null'; return }
9新增:if ($systems.Count -ne 1) { throw 'Unexpected Hyper-V management result.' }
10新增:$vm = Hyper-V\Get-VM -Id $targetId
11新增:if ($vm.Id -ne $targetId -or [string]::IsNullOrWhiteSpace([string]$vm.State) -or $vm.Generation -notin 1,2) {
12新增: throw 'Hyper-V instance changed.'
13新增:}
14新增:$disks = @(Hyper-V\Get-VMHardDiskDrive -VM $vm)
15新增:$adapters = @(Hyper-V\Get-VMNetworkAdapter -VM $vm)
16新增:$singleLocalVHDX = $false
17新增:$diskType = ''
18新增:if ($disks.Count -eq 1 -and $disks[0].Path) {
19新增: $path = [string]$disks[0].Path
20新增: if ($path -match '^[A-Za-z]:[\\/]') {
21新增: try {
22新增: if ([IO.DriveInfo]::new($path.Substring(0,3)).DriveType -ne 'Network') {
23新增: $disk = Hyper-V\Get-VHD -Path $path
24新增: if (!$disk -or !$disk.VhdFormat) { throw 'No local VHD metadata.' }
25新增: $singleLocalVHDX = [string]$disk.VhdFormat -eq 'VHDX'
26新增: $diskType = [string]$disk.VhdType
27新增: }
28新增: } catch {
29新增: $singleLocalVHDX = $null
30新增: }
31新增: }
32新增:}
33新增:$secureBoot = $false
34新增:$template = ''
35新增:$virtualTPM = $false
36新增:if ($vm.Generation -eq 2) {
37新增: $firmware = Hyper-V\Get-VMFirmware -VM $vm
38新增: $security = Hyper-V\Get-VMSecurity -VM $vm
39新增: if ($null -eq $security.TpmEnabled -or [string]$firmware.SecureBoot -notin 'On','Off') { throw 'Incomplete security configuration.' }
40新增: $secureBoot = [string]$firmware.SecureBoot -eq 'On'
41新增: $template = [string]$firmware.SecureBootTemplate
42新增: $virtualTPM = [bool]$security.TpmEnabled
43新增:}
44新增:[ordered]@{
45新增: state=[string]$vm.State; generation=[int]$vm.Generation
46新增: diskCount=$disks.Count; singleLocalVhdx=$singleLocalVHDX; diskType=$diskType
47新增: secureBoot=$secureBoot; secureBootTemplate=$template; virtualTpm=$virtualTPM
48新增: networkAdapterCount=$adapters.Count
49新增:} | ConvertTo-Json -Compress
新增internal/guestos/hyperv_instance_nonwindows.go+14 −0看文件
@@ -0,0 +1,14 @@
1新增://go:build !windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "context"
7新增: "errors"
8新增:
9新增: "github.com/google/uuid"
10新增:)
11新增:
12新增:func InspectHyperV(context.Context, uuid.UUID) (HyperVInspection, error) {
13新增: return HyperVInspection{}, errors.New("--vm-id 只支持查询本机 Windows Hyper-V 虚拟机")
14新增:}
新增internal/guestos/hyperv_instance_test.go+27 −0看文件
@@ -0,0 +1,27 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "os/exec"
5新增: "path/filepath"
6新增: "runtime"
7新增: "testing"
8新增:)
9新增:
10新增:func TestHyperVReadOnlyQuery(t *testing.T) {
11新增: shell := "pwsh"
12新增: if runtime.GOOS == "windows" {
13新增: shell = "powershell.exe"
14新增: }
15新增: binary, err := exec.LookPath(shell)
16新增: if err != nil {
17新增: t.Skipf("%s is not installed", shell)
18新增: }
19新增: query, err := filepath.Abs("hyperv_instance.ps1")
20新增: if err != nil {
21新增: t.Fatal(err)
22新增: }
23新增: cmd := exec.CommandContext(t.Context(), binary, "-NoProfile", "-NonInteractive", "-File", filepath.Join("testdata", "hyperv_instance.ps1"), "-Query", query)
24新增: if output, err := cmd.CombinedOutput(); err != nil {
25新增: t.Fatalf("Hyper-V query: %v\n%s", err, output)
26新增: }
27新增:}
新增internal/guestos/hyperv_instance_windows.go+70 −0看文件
@@ -0,0 +1,70 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "context"
5新增: _ "embed"
6新增: "encoding/json"
7新增: "errors"
8新增: "fmt"
9新增:
10新增: "github.com/google/uuid"
11新增:)
12新增:
13新增://go:embed hyperv_instance.ps1
14新增:var hyperVInstanceQuery string
15新增:
16新增:// InspectHyperV reads Hyper-V configuration without starting the VM, opening a
17新增:// guest session, enumerating unrelated VMs, or binding this VM to Cage.
18新增:func InspectHyperV(ctx context.Context, id uuid.UUID) (HyperVInspection, error) {
19新增: if id == uuid.Nil {
20新增: return HyperVInspection{}, errors.New("expected a non-empty Hyper-V VM GUID")
21新增: }
22新增: report := HyperVInspection{Inspection: Inspect(ctx), VMID: id.String(), Lookup: "unavailable"}
23新增: if !report.HostCheckPassed {
24新增: return report, nil
25新增: }
26新增: var actual HyperVInspection
27新增: if err := windowsHostManagerCall(ctx, id, "inspect", 0, 0, &actual); err != nil {
28新增: if ctx.Err() != nil {
29新增: return report, ctx.Err()
30新增: }
31新增: report.LookupDetail = err.Error()
32新增: return report, nil
33新增: }
34新增: if actual.VMID != id.String() || actual.Lookup != "found" || actual.VM == nil {
35新增: return report, errors.New("Windows 系统管理助手返回的虚拟机身份无效")
36新增: }
37新增: actual.Inspection = report.Inspection
38新增: return actual, nil
39新增:}
40新增:
41新增:func inspectHyperVNative(ctx context.Context, id uuid.UUID) (HyperVInspection, error) {
42新增: if id == uuid.Nil {
43新增: return HyperVInspection{}, errors.New("expected a non-empty Hyper-V VM GUID")
44新增: }
45新增: report := HyperVInspection{Inspection: Inspection{Guest: Windows11, HostCheckPassed: true, WorkbenchSupport: nativeWorkbenchSupport(Windows11, true)}, VMID: id.String(), Lookup: "unavailable"}
46新增: // UUID.String supplies only hexadecimal digits and dashes.
47新增: query := fmt.Sprintf("$targetId = [guid]'%s'\n", id.String()) + hyperVInstanceQuery
48新增: cmd, err := systemPowerShellQuery(ctx, query)
49新增: if err != nil {
50新增: return report, err
51新增: }
52新增: output, err := cmd.Output()
53新增: if ctx.Err() != nil {
54新增: return report, ctx.Err()
55新增: }
56新增: if err != nil {
57新增: report.LookupDetail = "无法读取该虚拟机的 Hyper-V 配置,请核对当前用户权限与虚拟机状态。"
58新增: return report, nil
59新增: }
60新增: if err := json.Unmarshal(output, &report.VM); err != nil {
61新增: return report, errors.New("Hyper-V 返回了无法识别的虚拟机配置")
62新增: }
63新增: if report.VM == nil {
64新增: report.Lookup = "not-found"
65新增: report.LookupDetail = "当前用户未查询到此标识的本机 Hyper-V 虚拟机。"
66新增: } else {
67新增: report.Lookup = "found"
68新增: }
69新增: return report, nil
70新增:}
新增internal/guestos/inspect.go+64 −0看文件
@@ -0,0 +1,64 @@
1新增:// Package guestos checks host prerequisites for a local guest system.
2新增:package guestos
3新增:
4新增:import (
5新增: "os"
6新增: "path/filepath"
7新增:)
8新增:
9新增:// Guest system IDs are shared with the workbench installer.
10新增:const (
11新增: Debian13 = "debian-13"
12新增: MacOS = "macos"
13新增: Windows11 = "windows-11"
14新增:)
15新增:
16新增:// MacRestore comes from Apple's compatibility catalog for this particular host.
17新增:type MacRestore struct {
18新增: Version string `json:"version"`
19新增: Build string `json:"build"`
20新增: URL string `json:"url"`
21新增: MinimumCPUs int `json:"minimumCPUs"`
22新增: MinimumMemoryBytes uint64 `json:"minimumMemoryBytes"`
23新增:}
24新增:
25新增:// Inspection keeps host capability separate from availability in the workbench.
26新增:type Inspection struct {
27新增: Guest string `json:"guest"`
28新增: HostCheckPassed bool `json:"hostCheckPassed"`
29新增: WorkbenchSupport string `json:"workbenchSupport"`
30新增: Detail string `json:"detail"`
31新增: Restore *MacRestore `json:"restore,omitempty"`
32新增:}
33新增:
34新增:// HasNativeWorkbenchKit checks the resources shipped alongside this backend.
35新增:// A standalone diagnostic binary can inspect a host without the desktop kit.
36新增:func HasNativeWorkbenchKit(executable, system string) bool {
37新增: var files []string
38新增: switch system {
39新增: case MacOS:
40新增: files = []string{"prepare-macos-media.sh", "provision-macos-workbench.sh", "project/cage-sshfs", "native-browser/macos-native-browser.mjs", "cage-finish-initial-setup"}
41新增: case Windows11:
42新增: files = []string{"new-windows-guest.ps1", "setup-windows-guest.ps1", "windows-host-image.ps1", "complete-windows-guest.ps1", "install-windows-host-manager.ps1", "payload/Cage.HyperVManager.exe", "payload/Cage.GuestClipboard.exe"}
43新增: default:
44新增: return false
45新增: }
46新增: for _, name := range files {
47新增: info, err := os.Stat(filepath.Join(filepath.Dir(executable), "guest-os", name))
48新增: if err != nil || !info.Mode().IsRegular() {
49新增: return false
50新增: }
51新增: }
52新增: return true
53新增:}
54新增:
55新增:func nativeWorkbenchSupport(system string, hostReady bool) string {
56新增: if !hostReady {
57新增: return "host-not-ready"
58新增: }
59新增: exe, err := os.Executable()
60新增: if err != nil || !HasNativeWorkbenchKit(exe, system) {
61新增: return "installation-kit-missing"
62新增: }
63新增: return "desktop-installer"
64新增:}
新增internal/guestos/inspect_darwin.go+17 −0看文件
@@ -0,0 +1,17 @@
1新增:package guestos
2新增:
3新增:import "context"
4新增:
5新增:func Inspect(ctx context.Context) Inspection {
6新增: r := Inspection{Guest: MacOS, WorkbenchSupport: nativeWorkbenchSupport(MacOS, false)}
7新增: image, err := probeMacHost(ctx)
8新增: if err != nil {
9新增: r.Detail = "无法查询本机兼容的 Apple 恢复镜像:" + err.Error()
10新增: return r
11新增: }
12新增: r.HostCheckPassed = true
13新增: r.WorkbenchSupport = nativeWorkbenchSupport(MacOS, true)
14新增: r.Restore = &image
15新增: r.Detail = "Apple 提供与此主机兼容的 macOS 恢复镜像。"
16新增: return r
17新增:}
新增internal/guestos/inspect_linux.go+26 −0看文件
@@ -0,0 +1,26 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "bytes"
5新增: "context"
6新增: "runtime"
7新增: "strings"
8新增:
9新增: "github.com/sylvinus/agent-vm/internal/host"
10新增:)
11新增:
12新增:func Inspect(_ context.Context) Inspection {
13新增: r := Inspection{Guest: Debian13, WorkbenchSupport: "supported"}
14新增: if runtime.GOARCH != "amd64" {
15新增: r.WorkbenchSupport = "unsupported-host"
16新增: r.Detail = "Linux 桌面发行包面向 x86_64 主机。"
17新增: return r
18新增: }
19新增: var details bytes.Buffer
20新增: r.HostCheckPassed = host.LinuxPrereqs(&details)
21新增: r.Detail = strings.TrimSpace(details.String())
22新增: if r.HostCheckPassed {
23新增: r.Detail = "已检测到 Debian 工作台所需的 Linux 虚拟化组件。"
24新增: }
25新增: return r
26新增:}
新增internal/guestos/inspect_other.go+9 −0看文件
@@ -0,0 +1,9 @@
1新增://go:build !darwin && !linux && !windows
2新增:
3新增:package guestos
4新增:
5新增:import "context"
6新增:
7新增:func Inspect(_ context.Context) Inspection {
8新增: return Inspection{WorkbenchSupport: "unsupported-host", Detail: "此平台没有 Cage 本机工作台。"}
9新增:}
新增internal/guestos/inspect_windows.go+8 −0看文件
@@ -0,0 +1,8 @@
1新增:package guestos
2新增:
3新增:import "context"
4新增:
5新增:func Inspect(ctx context.Context) Inspection {
6新增: ok, reason := probeWindowsHost(ctx)
7新增: return Inspection{Guest: Windows11, HostCheckPassed: ok, WorkbenchSupport: nativeWorkbenchSupport(Windows11, ok), Detail: reason}
8新增:}
新增internal/guestos/install_other.go+13 −0看文件
@@ -0,0 +1,13 @@
1新增://go:build !windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "context"
7新增: "errors"
8新增: "os/exec"
9新增:)
10新增:
11新增:func WindowsInstallCommand(context.Context, string, string, Installation) (*exec.Cmd, error) {
12新增: return nil, errors.New("Windows 客机需要 Windows 11 x64 Hyper-V 主机")
13新增:}
新增internal/guestos/install_windows.go+40 −0看文件
@@ -0,0 +1,40 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "context"
5新增: "crypto/sha256"
6新增: "fmt"
7新增: "os"
8新增:
9新增: "os/exec"
10新增: "path/filepath"
11新增:
12新增: "github.com/sylvinus/agent-vm/internal/cage"
13新增: "golang.org/x/sys/windows"
14新增:)
15新增:
16新增:func WindowsInstallCommand(ctx context.Context, profile, kit string, install Installation) (*exec.Cmd, error) {
17新增: system, err := windows.GetSystemDirectory()
18新增: if err != nil {
19新增: return nil, err
20新增: }
21新增: state, err := cage.StoragePhysicalPath(filepath.Join(profile, "state"))
22新增: if err != nil {
23新增: return nil, err
24新增: }
25新增: manifest, err := RequiredNativeComponents(kit, Windows11)
26新增: if err != nil {
27新增: return nil, err
28新增: }
29新增: manifestPath := filepath.Join(profile, "windows-components-required.json")
30新增: if err = WriteNativeComponentManifest(manifestPath, manifest); err != nil {
31新增: return nil, err
32新增: }
33新增: data, err := os.ReadFile(manifestPath)
34新增: if err != nil {
35新增: return nil, err
36新增: }
37新增: digest := fmt.Sprintf("%x", sha256.Sum256(data))
38新增: cmd := exec.CommandContext(ctx, filepath.Join(system, "WindowsPowerShell", "v1.0", "powershell.exe"), "-NoLogo", "-NoProfile", "-ExecutionPolicy", "RemoteSigned", "-File", filepath.Join(kit, "setup-windows-guest.ps1"), "-Profile", profile, "-State", state, "-InstallationID", install.ID.String(), "-IsoPath", install.Media, "-ExpectedIsoSha256", install.SHA256, "-ManifestPath", manifestPath, "-ManifestSHA256", digest)
39新增: return cmd, nil
40新增:}
新增internal/guestos/installation.go+254 −0看文件
@@ -0,0 +1,254 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "bytes"
5新增: "encoding/hex"
6新增: "encoding/json"
7新增: "errors"
8新增: "io"
9新增: "os"
10新增: "path/filepath"
11新增: "strings"
12新增:
13新增: "github.com/google/uuid"
14新增: "github.com/sylvinus/agent-vm/internal/hostimage"
15新增:)
16新增:
17新增:// Installation persists only the media choice and private instance identity.
18新增:// macOS secrets live separately in the Cage account's encrypted vault.
19新增:type Installation struct {
20新增: Version int `json:"version"`
21新增: System string `json:"system"`
22新增: Media string `json:"media,omitempty"`
23新增: SHA256 string `json:"sha256,omitempty"`
24新增: EditorTerms bool `json:"editor_terms,omitempty"`
25新增: ID uuid.UUID `json:"id"`
26新增: Source hostimage.Plan `json:"source,omitzero"`
27新增: // Empty preserves legacy host-clone records. LinuxImageSource selects a
28新增: // catalog image independently of the physical host OS.
29新增: SourceKind string `json:"source_kind,omitempty"`
30新增:}
31新增:
32新增:const installRecord = "guest-install.json"
33新增:const LinuxImageSource = "linux-image"
34新增:const Ubuntu2204 = "ubuntu-22.04"
35新增:
36新增:// Older installers could publish the binding before removing the temporary
37新增:// credential. Keep those profiles in setup until their original cleanup runs.
38新增:func WindowsCloneCleanupPending(profile string) (bool, error) {
39新增: install, err := LoadInstallation(profile)
40新增: if err != nil || install == nil || install.Source.Host.System != Windows11 {
41新增: return false, err
42新增: }
43新增: path := filepath.Join(profile, "windows-setup-"+strings.ReplaceAll(install.ID.String(), "-", "")+".dpapi")
44新增: _, err = os.Lstat(path)
45新增: if errors.Is(err, os.ErrNotExist) {
46新增: return false, nil
47新增: }
48新增: return err == nil, err
49新增:}
50新增:
51新增:func (i Installation) Validate() error {
52新增: if i.Version != 1 || i.ID == uuid.Nil || (i.System != MacOS && i.System != Windows11 && !hostimage.IsLinux(i.System)) {
53新增: return errors.New("客户机安装记录无效")
54新增: }
55新增: if i.SourceKind != "" && (i.SourceKind != LinuxImageSource || i.System != Ubuntu2204 || i.Source.Host.System != i.System) {
56新增: return errors.New("客户机镜像选择方式无效")
57新增: }
58新增: if i.Media != "" && (!filepath.IsAbs(i.Media) || strings.ContainsAny(i.Media, "\r\n\x00") || filepath.Clean(i.Media) != i.Media) {
59新增: return errors.New("请选择本机的安装镜像")
60新增: }
61新增: if i.Source.Host.System != "" {
62新增: if i.System != i.Source.Host.System || (i.System == Windows11 && !i.EditorTerms) {
63新增: return errors.New("本机系统安装选择无效,请重新检查")
64新增: }
65新增: if i.Media != "" && i.Media != i.Source.Path {
66新增: return errors.New("安装介质与已选择的本机系统来源不一致")
67新增: }
68新增: return i.Source.Validate()
69新增: }
70新增: if hostimage.IsLinux(i.System) {
71新增: return errors.New("缺少 Linux 本机系统安装来源")
72新增: }
73新增: if i.System == MacOS {
74新增: if i.SHA256 != "" || (i.Media != "" && !strings.EqualFold(filepath.Ext(i.Media), ".ipsw")) {
75新增: return errors.New("请选择 Apple 的 .ipsw 恢复镜像")
76新增: }
77新增: } else if hash, err := hex.DecodeString(i.SHA256); i.Media == "" || !i.EditorTerms || err != nil || len(hash) != 32 || !strings.EqualFold(filepath.Ext(i.Media), ".iso") {
78新增: return errors.New("请选择 Windows 11 x64 ISO,并填写这份镜像的完整 SHA-256")
79新增: }
80新增: return nil
81新增:}
82新增:
83新增:func LoadInstallation(profile string) (*Installation, error) {
84新增: path := filepath.Join(profile, installRecord)
85新增: info, err := os.Lstat(path)
86新增: if errors.Is(err, os.ErrNotExist) {
87新增: return nil, nil
88新增: }
89新增: if err != nil {
90新增: return nil, err
91新增: }
92新增: if !info.Mode().IsRegular() || info.Size() > 32<<10 {
93新增: return nil, errors.New("客户机安装记录无法读取")
94新增: }
95新增: data, err := os.ReadFile(path)
96新增: if err != nil {
97新增: return nil, err
98新增: }
99新增: var i Installation
100新增: decoder := json.NewDecoder(bytes.NewReader(data))
101新增: decoder.DisallowUnknownFields()
102新增: if decoder.Decode(&i) != nil || decoder.Decode(new(any)) != io.EOF {
103新增: return nil, errors.New("客户机安装记录格式无效")
104新增: }
105新增: if err := i.Validate(); err != nil {
106新增: return nil, err
107新增: }
108新增: if i.Source.Host.System != "" {
109新增: var ready struct {
110新增: ID uuid.UUID `json:"id"`
111新增: Source hostimage.Plan `json:"source"`
112新增: }
113新增: mediaPath := filepath.Join(profile, "guest-install-media-"+i.ID.String()+".json")
114新增: info, err := os.Lstat(mediaPath)
115新增: if err == nil {
116新增: if !info.Mode().IsRegular() || info.Size() > 32<<10 {
117新增: return nil, errors.New("已校验的安装材料记录无效")
118新增: }
119新增: data, readErr := os.ReadFile(mediaPath)
120新增: if readErr != nil || json.Unmarshal(data, &ready) != nil || ready.ID != i.ID {
121新增: return nil, errors.New("无法读取已校验的安装材料")
122新增: }
123新增: if err := matchPreparedMedia(i.Source, ready.Source); err != nil {
124新增: return nil, err
125新增: }
126新增: i.Source, i.Media = ready.Source, ready.Source.Path
127新增: i.SHA256 = strings.TrimPrefix(ready.Source.Digest, "sha256:")
128新增: } else if !errors.Is(err, os.ErrNotExist) {
129新增: return nil, err
130新增: }
131新增: }
132新增: return &i, i.Validate()
133新增:}
134新增:
135新增:func SaveInstallation(profile string, i Installation) error {
136新增: if err := i.Validate(); err != nil {
137新增: return err
138新增: }
139新增: if current, err := LoadInstallation(profile); err != nil {
140新增: return err
141新增: } else if current != nil {
142新增: if *current == i {
143新增: return nil
144新增: }
145新增: return errors.New("已有其他安装选择,请继续原安装")
146新增: }
147新增: data, err := json.Marshal(i)
148新增: if err != nil {
149新增: return err
150新增: }
151新增: return publishBinding(profile, installRecord, append(data, '\n'))
152新增:}
153新增:
154新增:func matchPreparedMedia(chosen, ready hostimage.Plan) error {
155新增: if err := ready.Validate(); err != nil {
156新增: return err
157新增: }
158新增: if ready.Path == "" || ready.Digest == "" || ready.Host != chosen.Host || ready.Version != chosen.Version || ready.Build != chosen.Build ||
159新增: ready.Format != chosen.Format || ready.URL != chosen.URL || (chosen.Digest != "" && ready.Digest != chosen.Digest) ||
160新增: (chosen.Bytes != 0 && ready.Bytes != chosen.Bytes) || (chosen.Path != "" && ready.Path != chosen.Path) ||
161新增: (chosen.Modified != 0 && ready.Modified != chosen.Modified) {
162新增: return errors.New("已校验的系统材料与原安装选择不一致")
163新增: }
164新增: return nil
165新增:}
166新增:
167新增:// RecordPreparedMedia publishes a create-only receipt. The original choice
168新增:// remains immutable throughout downloading, installation and concurrent retries.
169新增:func RecordPreparedMedia(profile string, id uuid.UUID, ready hostimage.Plan) error {
170新增: current, err := LoadInstallation(profile)
171新增: if err != nil {
172新增: return err
173新增: }
174新增: if current == nil || current.ID != id {
175新增: return errors.New("安装选择已变化")
176新增: }
177新增: if err := matchPreparedMedia(current.Source, ready); err != nil {
178新增: return err
179新增: }
180新增: data, err := json.Marshal(struct {
181新增: ID uuid.UUID `json:"id"`
182新增: Source hostimage.Plan `json:"source"`
183新增: }{id, ready})
184新增: if err != nil {
185新增: return err
186新增: }
187新增: return publishBinding(profile, "guest-install-media-"+id.String()+".json", data)
188新增:}
189新增:
190新增:func FinishLinuxInstallation(profile string, id uuid.UUID) error {
191新增: installed, err := LoadInstallation(profile)
192新增: if err != nil {
193新增: return err
194新增: }
195新增: if installed == nil || installed.ID != id || !hostimage.IsLinux(installed.System) {
196新增: return errors.New("Linux 安装记录已变化")
197新增: }
198新增: // Keep recovery information until the persistent image choice can be read.
199新增: system, err := hostimage.LinuxSystem(filepath.Join(profile, "state"))
200新增: if err != nil {
201新增: return err
202新增: }
203新增: if system != installed.System {
204新增: return errors.New("Linux 安装尚未保存所选系统,保留安装记录以便继续")
205新增: }
206新增: return os.Remove(filepath.Join(profile, installRecord))
207新增:}
208新增:
209新增:// UnstartedInstallation reports whether the choice can be changed while
210新增:// retaining every downloaded file and disk. A partial VM counts as started.
211新增:func UnstartedInstallation(profile string, i Installation) (bool, error) {
212新增: paths := []string{"macos-guest.json", "windows-guest.json", "windows-install-vm.txt",
213新增: filepath.Join("state", "windows-"+strings.ReplaceAll(i.ID.String(), "-", "")),
214新增: filepath.Join("state", "lima", "mac"), filepath.Join("state", "lima", "base-building"), filepath.Join("state", "lima", "base")}
215新增: for _, rel := range paths {
216新增: _, err := os.Lstat(filepath.Join(profile, rel))
217新增: if err == nil {
218新增: return false, nil
219新增: }
220新增: if !errors.Is(err, os.ErrNotExist) {
221新增: return false, err
222新增: }
223新增: }
224新增: return true, nil
225新增:}
226新增:
227新增:func ClearUnstartedInstallation(profile string, id uuid.UUID) error {
228新增: pending, err := LoadInstallation(profile)
229新增: if err != nil {
230新增: return err
231新增: }
232新增: if pending == nil || pending.ID != id {
233新增: return errors.New("客户机安装选择已改变")
234新增: }
235新增: canClear, err := UnstartedInstallation(profile, *pending)
236新增: if err != nil {
237新增: return err
238新增: }
239新增: if !canClear {
240新增: return errors.New("已开始创建客户机,请继续原安装")
241新增: }
242新增: if hostimage.IsLinux(pending.System) {
243新增: if err := hostimage.ClearLinuxTemplate(filepath.Join(profile, "state"), pending.Source); err != nil {
244新增: return err
245新增: }
246新增: }
247新增: return os.Remove(filepath.Join(profile, installRecord))
248新增:}
249新增:
250新增:// The Apple login surface accepts physical keys from the guest's initial US
251新增:// layout. Check this before downloading media or creating the local account.
252新增:func ValidMacOSInstallPassword(value string) bool {
253新增: return len(value) >= 8 && len(value) <= 256 && strings.IndexFunc(value, func(r rune) bool { return r < ' ' || r > '~' }) < 0
254新增:}
新增internal/guestos/installation_test.go+107 −0看文件
@@ -0,0 +1,107 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "bytes"
5新增: "crypto/ed25519"
6新增: "crypto/rand"
7新增: "github.com/google/uuid"
8新增: "golang.org/x/crypto/ssh"
9新增: "os"
10新增: "path/filepath"
11新增: "strings"
12新增: "testing"
13新增:)
14新增:
15新增:func TestInstallationKeepsChoiceAndRefusesToClearVM(t *testing.T) {
16新增: p := t.TempDir()
17新增: first := Installation{Version: 1, System: MacOS, ID: uuid.New()}
18新增: if err := SaveInstallation(p, first); err != nil {
19新增: t.Fatal(err)
20新增: }
21新增: if err := SaveInstallation(p, first); err != nil {
22新增: t.Fatal(err)
23新增: }
24新增: other := first
25新增: other.ID = uuid.New()
26新增: if err := SaveInstallation(p, other); err == nil {
27新增: t.Fatal("overwrote an active installation")
28新增: }
29新增: if err := ClearUnstartedInstallation(p, other.ID); err == nil {
30新增: t.Fatal("stale reset changed selection")
31新增: }
32新增: disk := filepath.Join(p, "state", "lima", "mac")
33新增: if err := os.MkdirAll(disk, 0700); err != nil {
34新增: t.Fatal(err)
35新增: }
36新增: if err := ClearUnstartedInstallation(p, first.ID); err == nil {
37新增: t.Fatal("forgot a partially installed VM")
38新增: }
39新增: got, err := LoadInstallation(p)
40新增: if err != nil || got == nil || *got != first {
41新增: t.Fatalf("changed original selection: %v %v", got, err)
42新增: }
43新增: if err := os.Remove(disk); err != nil {
44新增: t.Fatal(err)
45新增: }
46新增: if err := ClearUnstartedInstallation(p, first.ID); err != nil {
47新增: t.Fatal(err)
48新增: }
49新增: got, err = LoadInstallation(p)
50新增: if err != nil || got != nil {
51新增: t.Fatal("failed to clear media-only choice")
52新增: }
53新增:}
54新增:
55新增:func TestWindowsInstallRequiresMediaDigestAndEditorAgreement(t *testing.T) {
56新增: i := Installation{Version: 1, System: Windows11, ID: uuid.New(), Media: filepath.Join(t.TempDir(), "system.iso"), SHA256: strings.Repeat("a", 64)}
57新增: if err := i.Validate(); err == nil {
58新增: t.Fatal("accepted without the editor agreement")
59新增: }
60新增: i.EditorTerms = true
61新增: if err := i.Validate(); err != nil {
62新增: t.Fatal(err)
63新增: }
64新增: i.SHA256 = "bad"
65新增: if err := i.Validate(); err == nil {
66新增: t.Fatal("accepted an incomplete ISO digest")
67新增: }
68新增:}
69新增:
70新增:func TestMacSerialIdentityIsUnambiguous(t *testing.T) {
71新增: newKey := func() []byte {
72新增: pub, _, err := ed25519.GenerateKey(rand.Reader)
73新增: if err != nil {
74新增: t.Fatal(err)
75新增: }
76新增: key, err := ssh.NewPublicKey(pub)
77新增: if err != nil {
78新增: t.Fatal(err)
79新增: }
80新增: return ssh.MarshalAuthorizedKey(key)
81新增: }
82新增: key := newKey()
83新增: prefix := "CAGE-GUEST-HOST-KEY "
84新增: line := prefix + strings.TrimSpace(string(key)) + " guest\r\n"
85新增: got, err := parseInstallHostKey(strings.NewReader("startup\n" + line + line))
86新增: if err != nil || !bytes.Equal(key, got) {
87新增: t.Fatalf("valid serial identity: %v", err)
88新增: }
89新增: for _, body := range []string{"", "other " + line, line + prefix + "bad", line + prefix + string(newKey())} {
90新增: if _, err := parseInstallHostKey(strings.NewReader(body)); err == nil {
91新增: t.Fatal("accepted missing or inconsistent identity")
92新增: }
93新增: }
94新增:}
95新增:
96新增:func TestInitialMacPasswordCanBeEnteredAtTheLoginWindow(t *testing.T) {
97新增: for _, value := range []string{"Mix @#?9", strings.Repeat("!", 256)} {
98新增: if !ValidMacOSInstallPassword(value) {
99新增: t.Fatal("rejected an enterable password")
100新增: }
101新增: }
102新增: for _, value := range []string{"short", "中文输入示例密码", "abcde\tfgh", strings.Repeat("a", 257)} {
103新增: if ValidMacOSInstallPassword(value) {
104新增: t.Fatal("accepted an unsupported password")
105新增: }
106新增: }
107新增:}
新增internal/guestos/mac_host_darwin_arm64.go+121 −0看文件
@@ -0,0 +1,121 @@
1新增://go:build darwin && arm64 && cgo && !no_vz
2新增:
3新增:package guestos
4新增:
5新增:/*
6新增:#cgo CFLAGS: -x objective-c -fno-objc-arc
7新增:#cgo LDFLAGS: -framework Foundation -framework Security -framework Virtualization
8新增:#import <Security/SecTask.h>
9新增:#import <Virtualization/Virtualization.h>
10新增:#include <stdint.h>
11新增:
12新增:typedef struct {
13新增: const char *error;
14新增: const char *version;
15新增: const char *build;
16新增: const char *url;
17新增: uint64_t cpus;
18新增: uint64_t memory;
19新增:} cageMacRestore;
20新增:
21新增:extern void cageCompleteMacRestore(uintptr_t handle, cageMacRestore result);
22新增:
23新增:static bool cageHasVirtualizationEntitlement(void) {
24新增: SecTaskRef task = SecTaskCreateFromSelf(NULL);
25新增: if (!task) return false;
26新增: CFTypeRef value = SecTaskCopyValueForEntitlement(task, CFSTR("com.apple.security.virtualization"), NULL);
27新增: bool enabled = value && CFEqual(value, kCFBooleanTrue);
28新增: if (value) CFRelease(value);
29新增: CFRelease(task);
30新增: return enabled;
31新增:}
32新增:
33新增:// The Go binding's network lookup exposes only the URL. Apple's callback also
34新增:// contains the compatible hardware requirements, without reading the IPSW.
35新增:static void cageFetchMacRestore(uintptr_t handle) {
36新增: @autoreleasepool {
37新增: if (@available(macOS 12.0, *)) {
38新增: if (!cageHasVirtualizationEntitlement()) {
39新增: cageCompleteMacRestore(handle, (cageMacRestore){.error = "Cage must be signed with the com.apple.security.virtualization entitlement"});
40新增: return;
41新增: }
42新增: if (!VZVirtualMachine.supported) {
43新增: cageCompleteMacRestore(handle, (cageMacRestore){.error = "virtualization is unavailable on this Mac"});
44新增: return;
45新增: }
46新增: [VZMacOSRestoreImage fetchLatestSupportedWithCompletionHandler:^(VZMacOSRestoreImage *image, NSError *error) {
47新增: @autoreleasepool {
48新增: if (error) {
49新增: cageCompleteMacRestore(handle, (cageMacRestore){.error = error.localizedDescription.UTF8String});
50新增: return;
51新增: }
52新增: VZMacOSConfigurationRequirements *config = image.mostFeaturefulSupportedConfiguration;
53新增: if (!config.hardwareModel.supported) {
54新增: cageCompleteMacRestore(handle, (cageMacRestore){.error = "no macOS restore image supports this Mac"});
55新增: return;
56新增: }
57新增: NSOperatingSystemVersion os = image.operatingSystemVersion;
58新增: NSString *version = [NSString stringWithFormat:@"%ld.%ld.%ld",
59新增: (long)os.majorVersion, (long)os.minorVersion, (long)os.patchVersion];
60新增: cageCompleteMacRestore(handle, (cageMacRestore){
61新增: .version = version.UTF8String,
62新增: .build = image.buildVersion.UTF8String,
63新增: .url = image.URL.absoluteString.UTF8String,
64新增: .cpus = config.minimumSupportedCPUCount,
65新增: .memory = config.minimumSupportedMemorySize,
66新增: });
67新增: }
68新增: }];
69新增: } else {
70新增: cageCompleteMacRestore(handle, (cageMacRestore){.error = "macOS restore images require macOS 12 or later"});
71新增: }
72新增: }
73新增:}
74新增:*/
75新增:import "C"
76新增:
77新增:import (
78新增: "context"
79新增: "errors"
80新增: "runtime/cgo"
81新增:)
82新增:
83新增:type macRestoreResult struct {
84新增: image MacRestore
85新增: err error
86新增:}
87新增:
88新增:func probeMacHost(ctx context.Context) (MacRestore, error) {
89新增: if err := ctx.Err(); err != nil {
90新增: return MacRestore{}, err
91新增: }
92新增: done := make(chan macRestoreResult, 1)
93新增: C.cageFetchMacRestore(C.uintptr_t(cgo.NewHandle(done)))
94新增: select {
95新增: case <-ctx.Done():
96新增: return MacRestore{}, ctx.Err()
97新增: case result := <-done:
98新增: return result.image, result.err
99新增: }
100新增:}
101新增:
102新增:// The framework owns the request until completion. A late callback releases
103新增:// the handle and can finish even when its caller already timed out.
104新增://
105新增://export cageCompleteMacRestore
106新增:func cageCompleteMacRestore(handle C.uintptr_t, native C.cageMacRestore) {
107新增: h := cgo.Handle(handle)
108新增: done := h.Value().(chan macRestoreResult)
109新增: defer h.Delete()
110新增: if native.error != nil {
111新增: done <- macRestoreResult{err: errors.New(C.GoString(native.error))}
112新增: return
113新增: }
114新增: done <- macRestoreResult{image: MacRestore{
115新增: Version: C.GoString(native.version),
116新增: Build: C.GoString(native.build),
117新增: URL: C.GoString(native.url),
118新增: MinimumCPUs: int(native.cpus),
119新增: MinimumMemoryBytes: uint64(native.memory),
120新增: }}
121新增:}
新增internal/guestos/mac_host_unavailable_darwin.go+15 −0看文件
@@ -0,0 +1,15 @@
1新增://go:build darwin && (!arm64 || !cgo || no_vz)
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "context"
7新增: "errors"
8新增:)
9新增:
10新增:func probeMacHost(ctx context.Context) (MacRestore, error) {
11新增: if err := ctx.Err(); err != nil {
12新增: return MacRestore{}, err
13新增: }
14新增: return MacRestore{}, errors.New("macOS guests require Apple silicon and a Cage build with native Virtualization support")
15新增:}
新增internal/guestos/macos_login.go+24 −0看文件
@@ -0,0 +1,24 @@
1新增:package guestos
2新增:
3新增:// MacLoginRequest is the local one-instance login control protocol. No guest or
4新增:// host file paths, clipboard contents, or global shortcuts are accepted. Only
5新增:// the authenticated host may attach a stored password to fill-password.
6新增:type MacLoginRequest struct {
7新增: Action string `json:"action"`
8新增: Session string `json:"session,omitempty"`
9新增: Setup bool `json:"initial_setup,omitempty"`
10新增: Code int `json:"code"`
11新增: Shift bool `json:"shift"`
12新增: X int `json:"x"`
13新增: Y int `json:"y"`
14新增: DeltaX int `json:"delta_x,omitempty"`
15新增: DeltaY int `json:"delta_y,omitempty"`
16新增: Password string `json:"password,omitempty"`
17新增:}
18新增:type MacLoginReply struct {
19新增: MIME string `json:"mime,omitempty"`
20新增: Session string `json:"session,omitempty"`
21新增: Image []byte `json:"image,omitempty"`
22新增: Error string `json:"error,omitempty"`
23新增: Closed bool `json:"closed,omitempty"`
24新增:}
新增internal/guestos/macos_profile.go+200 −0看文件
@@ -0,0 +1,200 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "bytes"
5新增: "crypto/sha256"
6新增: "encoding/hex"
7新增: "encoding/json"
8新增: "errors"
9新增: "fmt"
10新增: "github.com/google/uuid"
11新增: "os"
12新增: "path/filepath"
13新增: "regexp"
14新增:
15新增: "golang.org/x/crypto/ssh"
16新增:)
17新增:
18新增:// MacOSProfile binds one prepared local VZ guest to its ordinary development account.
19新增:type MacOSProfile struct {
20新增: Version int `json:"version"`
21新增: Instance string `json:"instance"`
22新增: User string `json:"user"`
23新增: MachineID string `json:"machineID"`
24新增: SetupID string `json:"initial_setup,omitempty"`
25新增:}
26新增:
27新增:var macUser = regexp.MustCompile(`^[a-z][a-z0-9_]{0,30}$`)
28新增:
29新增:func macMachineID(profile string) (string, error) {
30新增: path := filepath.Join(profile, "state", "lima", "mac", "vz-identifier")
31新增: info, err := os.Lstat(path)
32新增: if err != nil {
33新增: return "", err
34新增: }
35新增: if !info.Mode().IsRegular() || info.Size() == 0 || info.Size() > 4096 {
36新增: return "", errors.New("invalid Apple virtual machine identifier")
37新增: }
38新增: data, err := os.ReadFile(path)
39新增: if err != nil {
40新增: return "", err
41新增: }
42新增: sum := sha256.Sum256(data)
43新增: return hex.EncodeToString(sum[:]), nil
44新增:}
45新增:
46新增:func LoadMacOSProfile(profile string) (*MacOSProfile, error) {
47新增: path := filepath.Join(profile, "macos-guest.json")
48新增: info, err := os.Lstat(path)
49新增: if errors.Is(err, os.ErrNotExist) {
50新增: return nil, nil
51新增: }
52新增: if err != nil {
53新增: return nil, err
54新增: }
55新增: if !info.Mode().IsRegular() || info.Size() > 4096 {
56新增: return nil, errors.New("invalid macOS guest profile")
57新增: }
58新增: data, err := os.ReadFile(path)
59新增: if err != nil {
60新增: return nil, err
61新增: }
62新增: var m MacOSProfile
63新增: if err := json.Unmarshal(data, &m); err != nil {
64新增: return nil, err
65新增: }
66新增: if m.Version != 1 || m.Instance != "mac" || !macUser.MatchString(m.User) || m.User == "root" {
67新增: return nil, errors.New("invalid macOS guest profile or login")
68新增: }
69新增: if m.SetupID != "" && !validSetupID(m.SetupID) {
70新增: return nil, errors.New("invalid first setup identity")
71新增: }
72新增: id, err := macMachineID(profile)
73新增: if err != nil {
74新增: return nil, err
75新增: }
76新增: if id != m.MachineID {
77新增: return nil, errors.New("the macOS guest differs from the machine bound to this profile")
78新增: }
79新增: return &m, nil
80新增:}
81新增:
82新增:// BindMacOSProfile takes an independently obtained guest host public key. Do
83新增:// not discover this key by scanning an unverified localhost SSH port.
84新增:func BindMacOSProfile(profile, user string, hostKey []byte) error {
85新增: return bindMacOSProfile(profile, user, hostKey, "")
86新增:}
87新增:
88新增:// BindNewMacOSProfile is called only by the fresh, resumable installer.
89新增:func BindNewMacOSProfile(profile, user string, hostKey []byte, id uuid.UUID) error {
90新增: install, err := LoadInstallation(profile)
91新增: if err != nil {
92新增: return err
93新增: }
94新增: if install == nil || id == uuid.Nil || install.ID != id || install.System != MacOS {
95新增: return errors.New("首次设置与当前安装记录不匹配")
96新增: }
97新增: return bindMacOSProfile(profile, user, hostKey, id.String())
98新增:}
99新增:
100新增:func validSetupID(id string) bool {
101新增: value, err := uuid.Parse(id)
102新增: return err == nil && value != uuid.Nil && value.String() == id
103新增:}
104新增:
105新增:func bindMacOSProfile(profile, user string, hostKey []byte, setupID string) error {
106新增: if !macUser.MatchString(user) || user == "root" {
107新增: return errors.New("supply the short name of the ordinary macOS guest account")
108新增: }
109新增: key, _, options, rest, err := ssh.ParseAuthorizedKey(hostKey)
110新增: if err != nil || len(options) != 0 || len(bytes.TrimSpace(rest)) != 0 || key.Type() != ssh.KeyAlgoED25519 {
111新增: return errors.New("expected one Ed25519 guest SSH host public key")
112新增: }
113新增: id, err := macMachineID(profile)
114新增: if err != nil {
115新增: return err
116新增: }
117新增: m := MacOSProfile{Version: 1, Instance: "mac", User: user, MachineID: id, SetupID: setupID}
118新增: data, err := json.Marshal(m)
119新增: if err != nil {
120新增: return err
121新增: }
122新增: if current, err := LoadMacOSProfile(profile); err != nil {
123新增: return err
124新增: } else if current != nil && *current != m {
125新增: return errors.New("this profile is already bound to another macOS guest account")
126新增: }
127新增: if err := publishBinding(profile, "macos-known-hosts", append([]byte("cage-macos "), ssh.MarshalAuthorizedKey(key)...)); err != nil {
128新增: return err
129新增: }
130新增: return publishBinding(profile, "macos-guest.json", append(data, '\n'))
131新增:}
132新增:
133新增:func publishBinding(profile, name string, data []byte) error {
134新增: temp, err := os.CreateTemp(profile, ".guest-binding-*")
135新增: if err != nil {
136新增: return err
137新增: }
138新增: defer os.Remove(temp.Name())
139新增: _, writeErr := temp.Write(data)
140新增: if err := errors.Join(writeErr, temp.Close()); err != nil {
141新增: return err
142新增: }
143新增: path := filepath.Join(profile, name)
144新增: if err := os.Link(temp.Name(), path); !errors.Is(err, os.ErrExist) {
145新增: return err
146新增: }
147新增: info, err := os.Lstat(path)
148新增: if err != nil || !info.Mode().IsRegular() || info.Size() != int64(len(data)) {
149新增: return fmt.Errorf("unexpected existing %s", name)
150新增: }
151新增: prior, err := os.ReadFile(path)
152新增: if err != nil || !bytes.Equal(data, prior) {
153新增: return fmt.Errorf("refusing to replace existing %s", name)
154新增: }
155新增: return nil
156新增:}
157新增:
158新增:// PinMacOSInstallHostKey persists only the host key, without enabling the workbench.
159新增:func PinMacOSInstallHostKey(profile string) error {
160新增: key, err := MacOSInstallHostKey(profile)
161新增: if err != nil {
162新增: return err
163新增: }
164新增: return publishBinding(profile, "macos-known-hosts", append([]byte("cage-macos "), key...))
165新增:}
166新增:
167新增:// FinishMacOSSetup removes the installation identity from the existing binding.
168新增:// Binding publication is create-only, so retrying an installer cannot reopen it.
169新增:func FinishMacOSSetup(profile, setupID string) error {
170新增: bound, err := LoadMacOSProfile(profile)
171新增: if err != nil {
172新增: return err
173新增: }
174新增: if bound == nil || !validSetupID(setupID) || bound.SetupID != setupID {
175新增: return errors.New("首次设置已关闭或安装实例已变更")
176新增: }
177新增: bound.SetupID = ""
178新增: data, err := json.Marshal(bound)
179新增: if err != nil {
180新增: return err
181新增: }
182新增: f, err := os.CreateTemp(profile, ".finish-guest-setup-*")
183新增: if err != nil {
184新增: return err
185新增: }
186新增: defer os.Remove(f.Name())
187新增: _, writeErr := f.Write(append(data, '\n'))
188新增: if err = errors.Join(writeErr, f.Sync(), f.Close()); err != nil {
189新增: return err
190新增: }
191新增: if err = os.Rename(f.Name(), filepath.Join(profile, "macos-guest.json")); err != nil {
192新增: return err
193新增: }
194新增: dir, err := os.Open(profile)
195新增: if err != nil {
196新增: return err
197新增: }
198新增: defer dir.Close()
199新增: return dir.Sync()
200新增:}
新增internal/guestos/macos_profile_test.go+104 −0看文件
@@ -0,0 +1,104 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "crypto/ed25519"
5新增: "crypto/rand"
6新增: "os"
7新增: "path/filepath"
8新增: "testing"
9新增:
10新增: "github.com/google/uuid"
11新增: "golang.org/x/crypto/ssh"
12新增:)
13新增:
14新增:func TestPreparedMacOSBindingRejectsChangedKeyAndDisk(t *testing.T) {
15新增: profile := t.TempDir()
16新增: dir := filepath.Join(profile, "state", "lima", "mac")
17新增: if err := os.MkdirAll(dir, 0700); err != nil {
18新增: t.Fatal(err)
19新增: }
20新增: identifier := filepath.Join(dir, "vz-identifier")
21新增: if err := os.WriteFile(identifier, []byte("one trial machine"), 0600); err != nil {
22新增: t.Fatal(err)
23新增: }
24新增: key := func() []byte {
25新增: pub, _, err := ed25519.GenerateKey(rand.Reader)
26新增: if err != nil {
27新增: t.Fatal(err)
28新增: }
29新增: p, err := ssh.NewPublicKey(pub)
30新增: if err != nil {
31新增: t.Fatal(err)
32新增: }
33新增: return ssh.MarshalAuthorizedKey(p)
34新增: }
35新增: pub := key()
36新增: if err := BindMacOSProfile(profile, "dev", pub); err != nil {
37新增: t.Fatal(err)
38新增: }
39新增: if err := BindMacOSProfile(profile, "dev", pub); err != nil {
40新增: t.Fatal(err)
41新增: }
42新增: if err := BindMacOSProfile(profile, "dev", key()); err == nil {
43新增: t.Error("changed host key accepted")
44新增: }
45新增: if err := BindMacOSProfile(profile, "root", pub); err == nil {
46新增: t.Error("root login accepted")
47新增: }
48新增: if m, err := LoadMacOSProfile(profile); err != nil || m.User != "dev" {
49新增: t.Fatal(m, err)
50新增: }
51新增: if err := os.WriteFile(identifier, []byte("replaced guest"), 0600); err != nil {
52新增: t.Fatal(err)
53新增: }
54新增: if _, err := LoadMacOSProfile(profile); err == nil {
55新增: t.Error("replacement machine accepted")
56新增: }
57新增:}
58新增:
59新增:func TestMacFirstSetupCanOnlySealItsNewGuest(t *testing.T) {
60新增: profile := t.TempDir()
61新增: dir := filepath.Join(profile, "state", "lima", "mac")
62新增: if err := os.MkdirAll(dir, 0700); err != nil {
63新增: t.Fatal(err)
64新增: }
65新增: if err := os.WriteFile(filepath.Join(dir, "vz-identifier"), []byte("new-mac"), 0600); err != nil {
66新增: t.Fatal(err)
67新增: }
68新增: pub, _, err := ed25519.GenerateKey(rand.Reader)
69新增: if err != nil {
70新增: t.Fatal(err)
71新增: }
72新增: key, err := ssh.NewPublicKey(pub)
73新增: if err != nil {
74新增: t.Fatal(err)
75新增: }
76新增: hostKey := ssh.MarshalAuthorizedKey(key)
77新增: id := uuid.New()
78新增: if err = BindNewMacOSProfile(profile, "cageuser", hostKey, id); err == nil {
79新增: t.Fatal("accepted missing install record")
80新增: }
81新增: if err = SaveInstallation(profile, Installation{Version: 1, System: MacOS, ID: id}); err != nil {
82新增: t.Fatal(err)
83新增: }
84新增: if err = BindNewMacOSProfile(profile, "cageuser", hostKey, id); err != nil {
85新增: t.Fatal(err)
86新增: }
87新增: if err = FinishMacOSSetup(profile, uuid.NewString()); err == nil {
88新增: t.Fatal("sealed unrelated install")
89新增: }
90新增: bound, err := LoadMacOSProfile(profile)
91新增: if err != nil || bound.SetupID != id.String() {
92新增: t.Fatal("lost pending setup")
93新增: }
94新增: if err = FinishMacOSSetup(profile, id.String()); err != nil {
95新增: t.Fatal(err)
96新增: }
97新增: if err = BindNewMacOSProfile(profile, "cageuser", hostKey, id); err == nil {
98新增: t.Fatal("a retried installer reopened setup")
99新增: }
100新增: bound, err = LoadMacOSProfile(profile)
101新增: if err != nil || bound.SetupID != "" {
102新增: t.Fatal("setup still open")
103新增: }
104新增:}
新增internal/guestos/macos_provision_test.go+29 −0看文件
@@ -0,0 +1,29 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "os"
5新增: "path/filepath"
6新增: "testing"
7新增:)
8新增:
9新增:func TestMacOSProvisionIdentity(t *testing.T) {
10新增: profile := t.TempDir()
11新增: dir := filepath.Join(profile, "state", "lima", "mac")
12新增: if err := os.MkdirAll(dir, 0700); err != nil {
13新增: t.Fatal(err)
14新增: }
15新增: for _, tc := range []struct{ config, want string }{
16新增: {"Host lima-mac\n User cage\n Port 12345\n", "cage"},
17新增: {"Host lima-mac\n User cageprovision\n Port 12345\n", "cageprovision"},
18新增: {"User cageuser\n", ""}, {"User root\n", ""}, {"Port 12345\n", ""},
19新增: {"User cage\nUser cageprovision\n", ""}, {"User cage extra\n", ""},
20新增: } {
21新增: if err := os.WriteFile(filepath.Join(dir, "ssh.config"), []byte(tc.config), 0600); err != nil {
22新增: t.Fatal(err)
23新增: }
24新增: got, err := MacOSProvisionUser(profile)
25新增: if got != tc.want || (err == nil) != (tc.want != "") {
26新增: t.Fatalf("%q: got %q, %v", tc.config, got, err)
27新增: }
28新增: }
29新增:}
新增internal/guestos/macos_serial.go+61 −0看文件
@@ -0,0 +1,61 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "bufio"
5新增: "bytes"
6新增: "errors"
7新增: "io"
8新增: "os"
9新增: "path/filepath"
10新增: "strings"
11新增:
12新增: "golang.org/x/crypto/ssh"
13新增:)
14新增:
15新增:// MacOSInstallHostKey reads the key written by the fresh guest's root-owned
16新增:// first-boot script to its VZ serial attachment, independent of loopback SSH.
17新增:func MacOSInstallHostKey(profile string) ([]byte, error) {
18新增: path := filepath.Join(profile, "state", "lima", "mac", "serialv.log")
19新增: info, err := os.Lstat(path)
20新增: if err != nil {
21新增: return nil, err
22新增: }
23新增: if !info.Mode().IsRegular() || info.Size() > 8<<20 {
24新增: return nil, errors.New("无效的 macOS 客机首次启动串口记录")
25新增: }
26新增: file, err := os.Open(path)
27新增: if err != nil {
28新增: return nil, err
29新增: }
30新增: defer file.Close()
31新增: return parseInstallHostKey(io.LimitReader(file, info.Size()))
32新增:}
33新增:
34新增:func parseInstallHostKey(input io.Reader) ([]byte, error) {
35新增: const prefix = "CAGE-GUEST-HOST-KEY "
36新增: scanner := bufio.NewScanner(input)
37新增: var found []byte
38新增: for scanner.Scan() {
39新增: line := strings.TrimSuffix(scanner.Text(), "\r")
40新增: keyLine, ok := strings.CutPrefix(line, prefix)
41新增: if !ok {
42新增: continue
43新增: }
44新增: key, _, opts, rest, err := ssh.ParseAuthorizedKey([]byte(keyLine))
45新增: if err != nil || key.Type() != ssh.KeyAlgoED25519 || len(opts) != 0 || len(rest) != 0 {
46新增: return nil, errors.New("虚拟 Mac 首次启动返回了无效的主机公钥")
47新增: }
48新增: candidate := ssh.MarshalAuthorizedKey(key)
49新增: if found != nil && !bytes.Equal(found, candidate) {
50新增: return nil, errors.New("虚拟 Mac 首次启动返回了不同的主机公钥")
51新增: }
52新增: found = candidate
53新增: }
54新增: if err := scanner.Err(); err != nil {
55新增: return nil, err
56新增: }
57新增: if found == nil {
58新增: return nil, errors.New("尚未从这台虚拟 Mac 的串口取得主机公钥")
59新增: }
60新增: return found, nil
61新增:}
新增internal/guestos/macos_ssh.go+79 −0看文件
@@ -0,0 +1,79 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "errors"
5新增: "os"
6新增: "path/filepath"
7新增: "strconv"
8新增: "strings"
9新增:)
10新增:
11新增:// Lima chooses a new loopback port on each boot. Read only that number from
12新增:// its generated config; use the provisioned VM key, user and identity file.
13新增:func MacOSSSHPort(config []byte) (int, error) {
14新增: var port int
15新增: for _, line := range strings.Split(string(config), "\n") {
16新增: fields := strings.Fields(line)
17新增: if len(fields) == 0 || !strings.EqualFold(fields[0], "port") {
18新增: continue
19新增: }
20新增: if len(fields) != 2 || port != 0 {
21新增: return 0, errors.New("macOS 客机 SSH 端口配置无效")
22新增: }
23新增: value, err := strconv.Atoi(fields[1])
24新增: if err != nil || value < 1 || value > 65535 {
25新增: return 0, errors.New("macOS 客机 SSH 端口配置无效")
26新增: }
27新增: port = value
28新增: }
29新增: if port == 0 {
30新增: return 0, errors.New("macOS 客机 SSH 端口尚未就绪")
31新增: }
32新增: return port, nil
33新增:}
34新增:
35新增:func MacOSSSHArgs(profile, user string) ([]string, error) {
36新增: data, err := os.ReadFile(filepath.Join(profile, "state", "lima", "mac", "ssh.config"))
37新增: if err != nil {
38新增: return nil, err
39新增: }
40新增: port, err := MacOSSSHPort(data)
41新增: if err != nil {
42新增: return nil, err
43新增: }
44新增: known := filepath.Join(profile, "macos-known-hosts")
45新增: // ssh -o parses each option as a config line; quote paths with spaces.
46新增: base := []string{"-q", "-e", "none", "-F", os.DevNull, "-p", strconv.Itoa(port),
47新增: "-l", user, "-i", filepath.Join(profile, "state", "lima", "_config", "user"),
48新增: "-o", "Hostname=127.0.0.1", "-o", "HostKeyAlias=cage-macos",
49新增: "-o", "StrictHostKeyChecking=yes", "-o", "HostKeyAlgorithms=ssh-ed25519",
50新增: "-o", "UserKnownHostsFile=" + strconv.Quote(known), "-o", "GlobalKnownHostsFile=" + os.DevNull,
51新增: "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "IdentityAgent=none",
52新增: "-o", "ForwardAgent=no", "-o", "ClearAllForwardings=yes", "-o", "ControlPath=none",
53新增: "-o", "ConnectTimeout=3", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=2"}
54新增: return base, nil
55新增:}
56新增:
57新增:// MacOSProvisionUser reads Lima's installation identity, including older VMs.
58新增:// Only these two dedicated identities may run privileged maintenance.
59新增:func MacOSProvisionUser(profile string) (string, error) {
60新增: data, err := os.ReadFile(filepath.Join(profile, "state", "lima", "mac", "ssh.config"))
61新增: if err != nil {
62新增: return "", err
63新增: }
64新增: var user string
65新增: for _, line := range strings.Split(string(data), "\n") {
66新增: fields := strings.Fields(line)
67新增: if len(fields) == 0 || !strings.EqualFold(fields[0], "User") {
68新增: continue
69新增: }
70新增: if len(fields) != 2 || user != "" || (fields[1] != "cage" && fields[1] != "cageprovision") {
71新增: return "", errors.New("macOS 客机安装账户配置无效")
72新增: }
73新增: user = fields[1]
74新增: }
75新增: if user == "" {
76新增: return "", errors.New("macOS 客机安装账户尚未就绪")
77新增: }
78新增: return user, nil
79新增:}
新增internal/guestos/maintenance_other.go+13 −0看文件
@@ -0,0 +1,13 @@
1新增://go:build !windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "context"
7新增: "errors"
8新增: "os/exec"
9新增:)
10新增:
11新增:func WindowsMaintenanceCommand(context.Context, string, string, string, bool) (*exec.Cmd, error) {
12新增: return nil, errors.New("Windows 客机维护需要其 Windows Hyper-V 主机")
13新增:}
新增internal/guestos/maintenance_windows.go+39 −0看文件
@@ -0,0 +1,39 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "context"
7新增: "crypto/sha256"
8新增: "errors"
9新增: "fmt"
10新增: "os"
11新增: "os/exec"
12新增: "path/filepath"
13新增:
14新增: "golang.org/x/sys/windows"
15新增:)
16新增:
17新增:func WindowsMaintenanceCommand(ctx context.Context, profile, kit, manifest string, tools bool) (*exec.Cmd, error) {
18新增: binding, err := LoadWindowsProfile(profile)
19新增: if err != nil {
20新增: return nil, err
21新增: }
22新增: if binding == nil {
23新增: return nil, errors.New("此配置尚未绑定 Windows 客机")
24新增: }
25新增: system, err := windows.GetSystemDirectory()
26新增: if err != nil {
27新增: return nil, err
28新增: }
29新增: data, err := os.ReadFile(manifest)
30新增: if err != nil {
31新增: return nil, err
32新增: }
33新增: hash := fmt.Sprintf("%x", sha256.Sum256(data))
34新增: args := []string{"-NoLogo", "-NoProfile", "-ExecutionPolicy", "RemoteSigned", "-File", filepath.Join(kit, "maintain-windows-workbench.ps1"), "-Profile", profile, "-ManifestPath", manifest, "-ManifestSHA256", hash}
35新增: if tools {
36新增: args = append(args, "-Tools")
37新增: }
38新增: return exec.CommandContext(ctx, filepath.Join(system, "WindowsPowerShell", "v1.0", "powershell.exe"), args...), nil
39新增:}
新增internal/guestos/testdata/hyperv_instance.ps1+55 −0看文件
@@ -0,0 +1,55 @@
1新增:# Exercise the bundled read-only query. No Hyper-V service or real VM is used.
2新增:param([Parameter(Mandatory)][string]$Query)
3新增:$ErrorActionPreference = 'Stop'
4新增:$targetId = [Guid]::NewGuid()
5新增:$global:hypervTestId = $targetId
6新增:$global:hypervCase = 'single'
7新增:function Get-CimInstance {
8新增: param($Namespace,$ClassName,$Filter)
9新增: if ($Namespace -ne 'root/virtualization/v2' -or $ClassName -ne 'Msvm_ComputerSystem' -or $Filter -ne "Name='$global:hypervTestId'") { throw 'Unscoped VM lookup.' }
10新增: if ($global:hypervCase -eq 'denied') { throw 'test management access denied' }
11新增: if ($global:hypervCase -ne 'absent') { [pscustomobject]@{Name=$global:hypervTestId} }
12新增:}
13新增:$fake = New-Module -Name Hyper-V -ScriptBlock {
14新增: function Get-VM {
15新增: param($Id)
16新增: if ($id -ne $global:hypervTestId) { throw 'Unscoped management lookup' }
17新增: $returned = if ($global:hypervCase -eq 'swapped') { [Guid]::NewGuid() } else { $id }
18新增: $generation = if ($global:hypervCase -eq 'legacy') { 1 } else { 2 }
19新增: $state = if ($global:hypervCase -eq 'connected') { 'Running' } else { 'Off' }
20新增: [pscustomobject]@{Id=$returned; Generation=$generation; State=$state}
21新增: }
22新增: function Get-VMHardDiskDrive {
23新增: param($VM)
24新增: [pscustomobject]@{Path='C:\private-qa\system.vhdx'}
25新增: if ($global:hypervCase -eq 'connected') { [pscustomobject]@{Path='C:\private-qa\second.vhdx'} }
26新增: }
27新增: function Get-VMNetworkAdapter { param($VM) if ($global:hypervCase -eq 'connected') { [pscustomobject]@{Name='adapter'} } }
28新增: function Get-VHD {
29新增: param($Path)
30新增: if ($global:hypervCase -eq 'disk-denied') { throw 'test disk metadata unavailable' }
31新增: if ($Path -cne 'C:\private-qa\system.vhdx') { throw 'Unexpected disk lookup' }
32新增: [pscustomobject]@{VhdFormat='VHDX'; VhdType='Dynamic'}
33新增: }
34新增: function Get-VMFirmware {param($VM) if ($VM.Generation -ne 2) { throw 'Legacy VM firmware query' }; [pscustomobject]@{SecureBoot='On'; SecureBootTemplate='MicrosoftWindows'} }
35新增: function Get-VMSecurity {param($VM) if ($VM.Generation -ne 2) { throw 'Legacy VM security query' }; [pscustomobject]@{TpmEnabled=$true} }
36新增: Export-ModuleMember -Function 'Get-*'
37新增:}
38新增:Import-Module $fake -Force
39新增:function Result { (& $Query) | ConvertFrom-Json }
40新增:$found = Result
41新增:if ($found.state -ne 'Off' -or $found.generation -ne 2 -or $found.diskCount -ne 1 -or !$found.singleLocalVhdx -or $found.diskType -ne 'Dynamic' -or !$found.secureBoot -or !$found.virtualTpm -or $found.networkAdapterCount -ne 0) { throw 'Invalid offline VM observation' }
42新增:if (($found | ConvertTo-Json -Compress).Contains('private-qa')) { throw 'Host disk path exposed' }
43新增:$global:hypervCase='connected'; $running=Result
44新增:if ($running.state -ne 'Running' -or $running.networkAdapterCount -ne 1 -or $running.diskCount -ne 2 -or $running.singleLocalVhdx) { throw 'Connected or multiple-disk VM misreported' }
45新增:$global:hypervCase='disk-denied'
46新增:if ($null -ne (Result).singleLocalVhdx) { throw 'Denied disk metadata reported as verified' }
47新增:$global:hypervCase='legacy'; $legacy = Result
48新增:if ($legacy.secureBoot -or $legacy.virtualTpm) { throw 'Legacy VM reported as secure boot/vTPM capable' }
49新增:$global:hypervCase='absent'; if ($null -ne (Result)) { throw 'Unexpected VM for missing ID' }
50新增:foreach ($testCase in @('denied', 'swapped')) {
51新增: $global:hypervCase = $testCase
52新增: $rejected = $false
53新增: try { $null = Result } catch { $rejected = $true }
54新增: if (!$rejected) { throw 'Access failure or changed VM identity treated as a valid lookup' }
55新增:}
新增internal/guestos/testdata/windows_lifecycle.ps1+29 −0看文件
@@ -0,0 +1,29 @@
1新增:param([Parameter(Mandatory)][string]$Query)
2新增:$ErrorActionPreference='Stop'
3新增:$script:targetId=[guid]'9e97dd9a-eb36-489a-bb1d-8d28a0d78682'
4新增:$script:state='Off';$script:nics=0;$script:mutations=0;$script:generation=2;$script:secure='On'
5新增:New-Module -Name Hyper-V -ScriptBlock {
6新增: function Get-VM { param([Guid]$Id) if ($Id -ne $script:targetId) { throw 'Unscoped VM operation.' }; [pscustomobject]@{Id=$Id;State=$script:state;Generation=$script:generation} }
7新增: function Get-VMFirmware { param($VM) if ($VM.Id -ne $script:targetId) { throw 'Wrong VM.' };[pscustomobject]@{SecureBoot=$script:secure;SecureBootTemplate='MicrosoftWindows'} }
8新增: function Get-VMSecurity { param($VM) [pscustomobject]@{TpmEnabled=$true} }
9新增: function Get-VMNetworkAdapter { param($VM) for($i=0;$i -lt $script:nics;$i++){[pscustomobject]@{Id=$i}} }
10新增: function Start-VM { param($VM) if($VM.Id -ne $script:targetId){throw 'Wrong VM.'};$script:state='Running';$script:mutations++ }
11新增: function Stop-VM { param($VM,[switch]$TurnOff,[switch]$Force) if($TurnOff -or $Force -or $VM.Id -ne $script:targetId){throw 'Unsafe stop.'};$script:state='Off';$script:mutations++ }
12新增: Export-ModuleMember -Function *
13新增:} | Import-Module -Force
14新增:# Module state is independent: configure it deliberately for each case.
15新增:$module=Get-Module Hyper-V
16新增:& $module { $script:targetId=[guid]'9e97dd9a-eb36-489a-bb1d-8d28a0d78682';$script:state='Off';$script:nics=0;$script:mutations=0;$script:generation=2;$script:secure='On' }
17新增:$action='start';$result=(& $Query)|ConvertFrom-Json
18新增:if($result.state -ne 'Running'){throw 'Start failed.'}
19新增:$action='stop';$result=(& $Query)|ConvertFrom-Json
20新增:if($result.state -ne 'Off'){throw 'Stop failed.'}
21新增:$action='stop';$result=(& $Query)|ConvertFrom-Json
22新增:if((& $module {$script:mutations}) -ne 2){throw 'Non-idempotent stop.'}
23新增:foreach($unsafe in 'nic','generation','secure'){
24新增: & $module { $script:nics=0;$script:generation=2;$script:secure='On' }
25新增: switch($unsafe){'nic'{& $module {$script:nics=1}}'generation'{& $module {$script:generation=1}}'secure'{& $module {$script:secure='Off'}}}
26新增: $action='start';$rejected=$false;try{& $Query | Out-Null}catch{$rejected=$true}
27新增: if(!$rejected -or (& $module {$script:mutations}) -ne 2){throw "Unsafe $unsafe guest started."}
28新增:}
29新增:'Windows lifecycle exact VM and safe shutdown checks passed.'
新增internal/guestos/testdata/windows_resources.ps1+26 −0看文件
@@ -0,0 +1,26 @@
1新增:param([Parameter(Mandatory)][string]$Query)
2新增:$ErrorActionPreference='Stop'
3新增:$targetId=[guid]'9e97dd9a-eb36-489a-bb1d-8d28a0d78682'
4新增:$module=New-Module -Name Hyper-V -ScriptBlock {
5新增: $script:id=[guid]'9e97dd9a-eb36-489a-bb1d-8d28a0d78682';$script:state='Off';$script:cpus=2;$script:start=5GB;$script:min=512MB;$script:max=1TB;$script:dynamic=$false;$script:mutations=0;$script:failMemory=$false
6新增: function Get-VM {param([Guid]$Id) if($Id -ne $script:id){throw 'Unscoped VM'};[pscustomobject]@{Id=$Id;State=$script:state;MemoryAssigned=0}}
7新增: function Get-VMProcessor {param($VM) if($VM.Id -ne $script:id){throw 'Wrong VM'};[pscustomobject]@{Count=$script:cpus}}
8新增: function Get-VMMemory {param($VM) if($VM.Id -ne $script:id){throw 'Wrong VM'};[pscustomobject]@{Startup=$script:start;Minimum=$script:min;Maximum=$script:max;DynamicMemoryEnabled=$script:dynamic}}
9新增: function Set-VMProcessor {param($VM,[int]$Count) if($VM.Id -ne $script:id -or $script:state -ne 'Off'){throw 'Unsafe apply'};$script:cpus=$Count;$script:mutations++}
10新增: function Set-VMMemory {param($VM,[bool]$DynamicMemoryEnabled,[long]$MinimumBytes,[long]$StartupBytes,[long]$MaximumBytes) if($VM.Id -ne $script:id -or $script:state -ne 'Off'){throw 'Unsafe memory apply'};if($script:failMemory -and $MaximumBytes -eq 16GB){throw 'Synthetic memory failure'};$script:min=$MinimumBytes;$script:start=$StartupBytes;$script:max=$MaximumBytes;$script:dynamic=$DynamicMemoryEnabled;$script:mutations++}
11新增: Export-ModuleMember -Function *
12新增:};$module|Import-Module -Force
13新增:$memoryGiB=0;$cpus=0;$read=(& $Query)|ConvertFrom-Json
14新增:if($read.cpus -ne 2 -or $read.memory_startup_bytes -ne 5GB -or (& $module {$script:mutations}) -ne 0){throw 'Read mutated resource settings'}
15新增:$memoryGiB=8;$cpus=4;$applied=(& $Query)|ConvertFrom-Json
16新增:if($applied.cpus -ne 4 -or $applied.memory_maximum_bytes -ne 8GB -or !$applied.dynamic_memory){throw 'Apply mismatch'}
17新增:& $module {$script:state='Running'}
18新增:$blocked=$false;try{& $Query|Out-Null}catch{$blocked=$true}
19新增:if(!$blocked -or (& $module {$script:mutations}) -ne 2){throw 'Running VM changed'}
20新增:& $module {$script:state='Off'};$memoryGiB=2
21新增:$blocked=$false;try{& $Query|Out-Null}catch{$blocked=$true}
22新增:if(!$blocked -or (& $module {$script:mutations}) -ne 2){throw 'Invalid memory changed VM'}
23新增:& $module {$script:failMemory=$true};$memoryGiB=16;$cpus=6
24新增:$blocked=$false;try{& $Query|Out-Null}catch{$blocked=$true}
25新增:if(!$blocked -or (& $module {$script:cpus}) -ne 4 -or (& $module {$script:max}) -ne 8GB){throw 'Failed apply did not restore prior resource settings'}
26新增:'Windows resource exact VM, readback, stopped apply and rollback passed.'
新增internal/guestos/windows_host_enrollment.go+70 −0看文件
@@ -0,0 +1,70 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "errors"
5新增: "github.com/google/uuid"
6新增:)
7新增:
8新增:// Options are captured by the original, unprivileged setup process. A pipe
9新增:// client cannot replace these paths, identities, or installation choices.
10新增:type WindowsHostEnrollmentOptions struct {
11新增: VMID uuid.UUID
12新增: InstallationID uuid.UUID
13新增: HostSID string
14新增: Profile string
15新增: State string
16新增: Pipe string
17新增: ParentPID uint32
18新增:}
19新增:
20新增:type windowsHostEnrollmentRequest struct {
21新增: Version int `json:"version"`
22新增: Challenge string `json:"challenge"`
23新增: Action string `json:"action"`
24新增: VMID uuid.UUID `json:"vm_id"`
25新增: GUIUserSID string `json:"gui_user_sid,omitempty"`
26新增: PID uint32 `json:"pid,omitempty"`
27新增: ProcessHandle uint64 `json:"process_handle,omitempty"`
28新增:}
29新增:
30新增:type windowsHostEnrollmentReply struct {
31新增: Version int `json:"version"`
32新增: OK bool `json:"ok"`
33新增: Challenge string `json:"challenge,omitempty"`
34新增: Authorized bool `json:"authorized,omitempty"`
35新增: Error string `json:"error,omitempty"`
36新增:}
37新增:
38新增:func (request windowsHostEnrollmentRequest) validate(vm uuid.UUID, owner bool, guestSID string) error {
39新增: if request.Version != 1 || request.VMID != vm {
40新增: return errors.New("enrollment_request_invalid")
41新增: }
42新增: if owner {
43新增: switch request.Action {
44新增: case "ready", "stop":
45新增: if request.PID != 0 || request.ProcessHandle != 0 || request.GUIUserSID != "" {
46新增: return errors.New("enrollment_request_invalid")
47新增: }
48新增: case "allow-admin":
49新增: if request.PID == 0 || request.ProcessHandle == 0 || request.GUIUserSID != "" {
50新增: return errors.New("enrollment_request_invalid")
51新增: }
52新增: default:
53新增: return errors.New("enrollment_action_invalid")
54新增: }
55新增: } else {
56新增: if request.PID != 0 || request.ProcessHandle != 0 || !windowsGUISID.MatchString(request.GUIUserSID) || guestSID != "" && request.GUIUserSID != guestSID {
57新增: return errors.New("enrollment_request_invalid")
58新增: }
59新增: switch request.Action {
60新增: case "deliver-gui", "deliver-packet":
61新增: case "finalize":
62新增: if guestSID == "" {
63新增: return errors.New("enrollment_request_invalid")
64新增: }
65新增: default:
66新增: return errors.New("enrollment_action_invalid")
67新增: }
68新增: }
69新增: return nil
70新增:}
新增internal/guestos/windows_host_enrollment_test.go+42 −0看文件
@@ -0,0 +1,42 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "github.com/google/uuid"
5新增: "testing"
6新增:)
7新增:
8新增:func TestWindowsHostEnrollmentFixedAuthorityAndRole(t *testing.T) {
9新增: vm := uuid.New()
10新增: sid := "S-1-5-21-1-2-3-1001"
11新增: valid := windowsHostEnrollmentRequest{Version: 1, VMID: vm, Action: "deliver-gui", GUIUserSID: sid}
12新增: if err := valid.validate(vm, false, ""); err != nil {
13新增: t.Fatal("authenticated initial GUI identity rejected", err)
14新增: }
15新增: if err := valid.validate(vm, true, ""); err == nil {
16新增: t.Fatal("ordinary owner was allowed to act as the elevated sender")
17新增: }
18新增: if err := valid.validate(uuid.New(), false, ""); err == nil {
19新增: t.Fatal("other VM could replace fixed enrollment scope")
20新增: }
21新增: if err := valid.validate(vm, false, "S-1-5-21-1-2-3-1002"); err == nil {
22新增: t.Fatal("guest identity could change after first authenticated binding")
23新增: }
24新增: valid.Action = "finalize"
25新增: if valid.validate(vm, false, "") == nil {
26新增: t.Fatal("unbound guest could finalize")
27新增: }
28新增: if err := valid.validate(vm, false, sid); err != nil {
29新增: t.Fatal(err)
30新增: }
31新增: valid.ProcessHandle = 99
32新增: if valid.validate(vm, false, sid) == nil {
33新增: t.Fatal("admin delivery accepted owner control fields")
34新增: }
35新增: owner := windowsHostEnrollmentRequest{Version: 1, VMID: vm, Action: "allow-admin", PID: 12, ProcessHandle: 34}
36新增: if err := owner.validate(vm, true, ""); err != nil {
37新增: t.Fatal(err)
38新增: }
39新增: if owner.validate(vm, false, sid) == nil {
40新增: t.Fatal("admin sender could replace original parent's authorization")
41新增: }
42新增:}
新增internal/guestos/windows_host_enrollment_windows.go+637 −0看文件
@@ -0,0 +1,637 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "bufio"
7新增: "bytes"
8新增: "context"
9新增: "crypto/rand"
10新增: "crypto/sha256"
11新增: "crypto/subtle"
12新增: "encoding/base64"
13新增: "encoding/json"
14新增: "errors"
15新增: "io"
16新增: "net"
17新增: "os"
18新增: "path/filepath"
19新增: "runtime"
20新增: "slices"
21新增: "strings"
22新增: "sync"
23新增: "time"
24新增: "unsafe"
25新增:
26新增: "github.com/Microsoft/go-winio"
27新增: "github.com/google/uuid"
28新增: "github.com/sylvinus/agent-vm/internal/paths"
29新增: "golang.org/x/sys/windows"
30新增:)
31新增:
32新增:const enrollmentWireLimit = 16 << 10
33新增:
34新增:type enrollmentProcess struct {
35新增: handle windows.Handle
36新增: pid uint32
37新增: started uint64
38新增: image string
39新增:}
40新增:
41新增:func enrollmentProcessFromHandle(handle windows.Handle) (enrollmentProcess, error) {
42新增: var value enrollmentProcess
43新增: pid, err := windows.GetProcessId(handle)
44新增: if err != nil || pid == 0 {
45新增: return value, errors.New("enrollment_process_invalid")
46新增: }
47新增: var created, exited, kernel, user windows.Filetime
48新增: if windows.GetProcessTimes(handle, &created, &exited, &kernel, &user) != nil {
49新增: return value, errors.New("enrollment_process_invalid")
50新增: }
51新增: buffer := make([]uint16, 32768)
52新增: size := uint32(len(buffer))
53新增: if windows.QueryFullProcessImageName(handle, 0, &buffer[0], &size) != nil || size == 0 || size >= uint32(len(buffer)) {
54新增: return value, errors.New("enrollment_process_invalid")
55新增: }
56新增: value = enrollmentProcess{handle: handle, pid: pid, started: uint64(created.HighDateTime)<<32 | uint64(created.LowDateTime), image: windows.UTF16ToString(buffer[:size])}
57新增: return value, nil
58新增:}
59新增:
60新增:func (process enrollmentProcess) alive() bool {
61新增: if process.handle == 0 {
62新增: return false
63新增: }
64新增: state, err := windows.WaitForSingleObject(process.handle, 0)
65新增: if err != nil || state != uint32(windows.WAIT_TIMEOUT) {
66新增: return false
67新增: }
68新增: fresh, err := enrollmentProcessFromHandle(process.handle)
69新增: return err == nil && fresh.pid == process.pid && fresh.started == process.started && strings.EqualFold(fresh.image, process.image)
70新增:}
71新增:
72新增:type windowsHostEnrollment struct {
73新增: options WindowsHostEnrollmentOptions
74新增: installation Installation
75新增: instance, stage string
76新增: owner enrollmentProcess
77新增: admin enrollmentProcess
78新增: guestSID string
79新增: finalized bool
80新增: mu sync.Mutex
81新增:}
82新增:
83新增:func newWindowsHostEnrollment(options WindowsHostEnrollmentOptions) (*windowsHostEnrollment, error) {
84新增: token := windows.GetCurrentProcessToken()
85新增: user, err := token.GetTokenUser()
86新增: if err != nil || token.IsElevated() || user.User.Sid.String() != options.HostSID || options.ParentPID == 0 || options.VMID == uuid.Nil || options.InstallationID == uuid.Nil ||
87新增: !filepath.IsAbs(options.Profile) || !filepath.IsAbs(options.State) || strings.ContainsAny(options.Profile+options.State, "\x00\r\n") ||
88新增: !(strings.HasPrefix(options.HostSID, "S-1-5-21-") || strings.HasPrefix(options.HostSID, "S-1-12-1-")) ||
89新增: !strings.HasPrefix(options.Pipe, "Cage.Enroll.") || len(options.Pipe) > 180 || strings.ContainsAny(options.Pipe, "\\/:\x00\r\n") {
90新增: return nil, errors.New("enrollment_original_user_required")
91新增: }
92新增: var basic struct{ ExitStatus, PEB, Affinity, Priority, PID, Parent uintptr }
93新增: var returned uint32
94新增: if windows.NtQueryInformationProcess(windows.CurrentProcess(), windows.ProcessBasicInformation, unsafe.Pointer(&basic), uint32(unsafe.Sizeof(basic)), &returned) != nil || uint32(basic.Parent) != options.ParentPID {
95新增: return nil, errors.New("enrollment_parent_invalid")
96新增: }
97新增: handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.SYNCHRONIZE, false, options.ParentPID)
98新增: if err != nil {
99新增: return nil, errors.New("enrollment_parent_invalid")
100新增: }
101新增: owner, err := enrollmentProcessFromHandle(handle)
102新增: if err != nil {
103新增: windows.CloseHandle(handle)
104新增: return nil, err
105新增: }
106新增: var parentToken windows.Token
107新增: if windows.OpenProcessToken(handle, windows.TOKEN_QUERY, &parentToken) != nil {
108新增: windows.CloseHandle(handle)
109新增: return nil, errors.New("enrollment_parent_invalid")
110新增: }
111新增: parentUser, err := parentToken.GetTokenUser()
112新增: parentToken.Close()
113新增: system, systemErr := windows.GetSystemDirectory()
114新增: expected := filepath.Join(system, "WindowsPowerShell", "v1.0", "powershell.exe")
115新增: if err != nil || parentUser.User.Sid.String() != options.HostSID || systemErr != nil || !strings.EqualFold(owner.image, expected) || !owner.alive() {
116新增: windows.CloseHandle(handle)
117新增: return nil, errors.New("enrollment_parent_invalid")
118新增: }
119新增: profile, err := paths.Resolve(options.Profile)
120新增: if err != nil {
121新增: windows.CloseHandle(handle)
122新增: return nil, errors.New("enrollment_profile_invalid")
123新增: }
124新增: state, err := paths.Resolve(options.State)
125新增: if err != nil {
126新增: windows.CloseHandle(handle)
127新增: return nil, errors.New("enrollment_profile_invalid")
128新增: }
129新增: anchor, err := paths.Resolve(filepath.Join(profile, "state"))
130新增: if err != nil || !strings.EqualFold(anchor, state) {
131新增: windows.CloseHandle(handle)
132新增: return nil, errors.New("enrollment_profile_invalid")
133新增: }
134新增: options.Profile, options.State = profile, state
135新增: installation, err := LoadInstallation(profile)
136新增: if err != nil || installation == nil || installation.System != Windows11 || installation.ID != options.InstallationID {
137新增: windows.CloseHandle(handle)
138新增: return nil, errors.New("enrollment_installation_changed")
139新增: }
140新增: instance := filepath.Join(state, "windows-"+strings.ReplaceAll(options.InstallationID.String(), "-", ""))
141新增: value := &windowsHostEnrollment{options: options, installation: *installation, instance: instance, stage: filepath.Join(instance, "cage-workbench", "pair"), owner: owner}
142新增: if err = value.assertScope(); err != nil {
143新增: windows.CloseHandle(handle)
144新增: return nil, err
145新增: }
146新增: if _, err = os.Lstat(WindowsProfilePath(profile)); !errors.Is(err, os.ErrNotExist) {
147新增: windows.CloseHandle(handle)
148新增: return nil, errors.New("enrollment_existing_profile_preserved")
149新增: }
150新增: if binding, err := LoadWindowsProfile(value.stage); err != nil {
151新增: windows.CloseHandle(handle)
152新增: return nil, errors.New("enrollment_existing_pairing_preserved")
153新增: } else if binding != nil {
154新增: if err = value.bindingValid(*binding); err != nil {
155新增: windows.CloseHandle(handle)
156新增: return nil, err
157新增: }
158新增: value.guestSID = binding.GUIUserSID
159新增: }
160新增: return value, nil
161新增:}
162新增:
163新增:func (value *windowsHostEnrollment) assertScope() error {
164新增: if !value.owner.alive() {
165新增: return errors.New("enrollment_parent_exited")
166新增: }
167新增: current, err := LoadInstallation(value.options.Profile)
168新增: if err != nil || current == nil || *current != value.installation {
169新增: return errors.New("enrollment_installation_changed")
170新增: }
171新增: receipt, err := os.ReadFile(filepath.Join(value.options.Profile, "windows-install-vm.txt"))
172新增: if err == nil && len(receipt) > 80 {
173新增: return errors.New("enrollment_vm_changed")
174新增: }
175新增: id, parse := uuid.Parse(strings.TrimSpace(string(receipt)))
176新增: if err != nil || parse != nil || id != value.options.VMID {
177新增: return errors.New("enrollment_vm_changed")
178新增: }
179新增: state, err := paths.Resolve(filepath.Join(value.options.Profile, "state"))
180新增: if err != nil || !strings.EqualFold(state, value.options.State) {
181新增: return errors.New("enrollment_profile_changed")
182新增: }
183新增: return nil
184新增:}
185新增:
186新增:func (value *windowsHostEnrollment) bindingValid(binding WindowsProfile) error {
187新增: if binding.VMID != value.options.VMID || !strings.EqualFold(filepath.Clean(binding.InstanceDirectory), value.instance) ||
188新增: !strings.EqualFold(filepath.Clean(binding.RelayExecutable), filepath.Join(value.stage, "Cage.GuestClipboard.exe")) ||
189新增: !strings.EqualFold(filepath.Clean(binding.PairingFile), filepath.Join(value.stage, "pairing.dpapi")) ||
190新增: binding.NetworkPairingFile != "" && !strings.EqualFold(filepath.Clean(binding.NetworkPairingFile), filepath.Join(value.stage, "packet.dpapi")) ||
191新增: value.guestSID != "" && binding.GUIUserSID != value.guestSID {
192新增: return errors.New("enrollment_binding_changed")
193新增: }
194新增: return nil
195新增:}
196新增:
197新增:func (value *windowsHostEnrollment) authorizeAdmin(request windowsHostEnrollmentRequest) error {
198新增: if value.admin.handle != 0 || request.PID == 0 || request.ProcessHandle == 0 || request.ProcessHandle > 0x7fffffffffffffff {
199新增: return errors.New("enrollment_admin_invalid")
200新增: }
201新增: handle := windows.Handle(request.ProcessHandle)
202新增: process, err := enrollmentProcessFromHandle(handle)
203新增: system, systemErr := windows.GetSystemDirectory()
204新增: if err != nil || systemErr != nil || process.pid != request.PID || !strings.EqualFold(process.image, filepath.Join(system, "WindowsPowerShell", "v1.0", "powershell.exe")) || !process.alive() {
205新增: windows.CloseHandle(handle)
206新增: return errors.New("enrollment_admin_invalid")
207新增: }
208新增: value.admin = process
209新增: return nil
210新增:}
211新增:
212新增:func cryptHostEnrollment(data []byte, vm uuid.UUID, sid string, protect bool) ([]byte, error) {
213新增: input := make([]byte, len(data))
214新增: copy(input, data)
215新增: defer clear(input)
216新增: entropy := sha256.Sum256([]byte("Cage.HyperV.v1:" + vm.String() + ":" + sid))
217新增: in := windows.DataBlob{Size: uint32(len(input)), Data: &input[0]}
218新增: salt := windows.DataBlob{Size: 32, Data: &entropy[0]}
219新增: var output windows.DataBlob
220新增: var err error
221新增: if protect {
222新增: err = windows.CryptProtectData(&in, nil, &salt, 0, nil, windows.CRYPTPROTECT_UI_FORBIDDEN, &output)
223新增: } else {
224新增: err = windows.CryptUnprotectData(&in, nil, &salt, 0, nil, windows.CRYPTPROTECT_UI_FORBIDDEN, &output)
225新增: }
226新增: runtime.KeepAlive(input)
227新增: runtime.KeepAlive(entropy)
228新增: if output.Data != nil {
229新增: defer func() {
230新增: if output.Size <= enrollmentWireLimit {
231新增: clear(unsafe.Slice(output.Data, int(output.Size)))
232新增: }
233新增: windows.LocalFree(windows.Handle(unsafe.Pointer(output.Data)))
234新增: }()
235新增: }
236新增: if err != nil || output.Data == nil || output.Size == 0 || output.Size > enrollmentWireLimit {
237新增: return nil, errors.New("enrollment_current_user_crypto_failed")
238新增: }
239新增: result := append([]byte(nil), unsafe.Slice(output.Data, int(output.Size))...)
240新增: return result, nil
241新增:}
242新增:
243新增:func (value *windowsHostEnrollment) privateKey(path string) ([]byte, error) {
244新增: info, err := os.Lstat(path)
245新增: if err != nil || !info.Mode().IsRegular() || info.Size() < 1 || info.Size() > enrollmentWireLimit {
246新增: return nil, errors.New("enrollment_existing_pairing_preserved")
247新增: }
248新增: name, _ := windows.UTF16PtrFromString(path)
249新增: attributes, err := windows.GetFileAttributes(name)
250新增: if err != nil || attributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 {
251新增: return nil, errors.New("enrollment_existing_pairing_preserved")
252新增: }
253新增: sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION)
254新增: if err != nil {
255新增: return nil, errors.New("enrollment_existing_pairing_preserved")
256新增: }
257新增: owner, _, err := sd.Owner()
258新增: control, _, controlErr := sd.Control()
259新增: acl, _, aclErr := sd.DACL()
260新增: if err != nil || owner == nil || owner.String() != value.options.HostSID || controlErr != nil || control&windows.SE_DACL_PROTECTED == 0 || aclErr != nil || acl == nil {
261新增: return nil, errors.New("enrollment_existing_pairing_preserved")
262新增: }
263新增: for i := uint32(0); i < uint32(acl.AceCount); i++ {
264新增: var ace *windows.ACCESS_ALLOWED_ACE
265新增: if windows.GetAce(acl, i, &ace) != nil || ace.Header.AceType != windows.ACCESS_ALLOWED_ACE_TYPE {
266新增: return nil, errors.New("enrollment_existing_pairing_preserved")
267新增: }
268新增: sid := (*windows.SID)(unsafe.Pointer(&ace.SidStart))
269新增: if sid.String() != value.options.HostSID && !sid.IsWellKnown(windows.WinBuiltinAdministratorsSid) && !sid.IsWellKnown(windows.WinLocalSystemSid) {
270新增: return nil, errors.New("enrollment_existing_pairing_preserved")
271新增: }
272新增: }
273新增: data, err := os.ReadFile(path)
274新增: if err != nil {
275新增: return nil, errors.New("enrollment_existing_pairing_preserved")
276新增: }
277新增: return data, nil
278新增:}
279新增:
280新增:func (value *windowsHostEnrollment) storeKey(ctx context.Context, kind, sid string, key []byte) error {
281新增: if ctx.Err() != nil {
282新增: return errors.New("enrollment_cancelled")
283新增: }
284新增: if len(key) != 32 || !windowsGUISID.MatchString(sid) || value.guestSID != "" && value.guestSID != sid {
285新增: return errors.New("enrollment_guest_changed")
286新增: }
287新增: if err := value.assertScope(); err != nil {
288新增: return err
289新增: }
290新增: if !value.admin.alive() {
291新增: return errors.New("enrollment_admin_exited")
292新增: }
293新增: value.guestSID = sid
294新增: name := "pairing.dpapi"
295新增: if kind == "deliver-packet" {
296新增: name = "packet.dpapi"
297新增: }
298新增: path := filepath.Join(value.stage, name)
299新增: if _, err := os.Lstat(path); err == nil {
300新增: data, err := value.privateKey(path)
301新增: if err != nil {
302新增: return err
303新增: }
304新增: old, err := cryptHostEnrollment(data, value.options.VMID, sid, false)
305新增: if err != nil {
306新增: return err
307新增: }
308新增: defer clear(old)
309新增: if subtle.ConstantTimeCompare(old, key) != 1 {
310新增: return errors.New("enrollment_existing_pairing_preserved")
311新增: }
312新增: return nil
313新增: } else if !errors.Is(err, os.ErrNotExist) {
314新增: return errors.New("enrollment_existing_pairing_preserved")
315新增: }
316新增: stage, err := paths.Resolve(value.stage)
317新增: if err != nil || !strings.EqualFold(stage, value.stage) {
318新增: return errors.New("enrollment_profile_changed")
319新增: }
320新增: data, err := cryptHostEnrollment(key, value.options.VMID, sid, true)
321新增: if err != nil {
322新增: return err
323新增: }
324新增: sd, err := windows.SecurityDescriptorFromString("O:" + value.options.HostSID + "D:P(A;;FA;;;" + value.options.HostSID + ")(A;;FA;;;SY)(A;;FA;;;BA)")
325新增: if err != nil {
326新增: return errors.New("enrollment_permissions_invalid")
327新增: }
328新增: attributes := windows.SecurityAttributes{Length: uint32(unsafe.Sizeof(windows.SecurityAttributes{})), SecurityDescriptor: sd}
329新增: pathPtr, _ := windows.UTF16PtrFromString(path)
330新增: if ctx.Err() != nil || !value.admin.alive() {
331新增: return errors.New("enrollment_cancelled")
332新增: }
333新增: handle, err := windows.CreateFile(pathPtr, windows.FILE_WRITE_DATA|windows.READ_CONTROL|windows.WRITE_DAC|windows.DELETE, 0, &attributes, windows.CREATE_NEW, windows.FILE_ATTRIBUTE_NORMAL, 0)
334新增: runtime.KeepAlive(sd)
335新增: if err != nil {
336新增: return errors.New("enrollment_pairing_not_saved")
337新增: }
338新增: file := os.NewFile(uintptr(handle), path)
339新增: completed := false
340新增: defer func() {
341新增: if !completed {
342新增: discard := byte(1)
343新增: _ = windows.SetFileInformationByHandle(handle, windows.FileDispositionInfo, &discard, 1)
344新增: }
345新增: file.Close()
346新增: }()
347新增: if _, err = file.Write(data); err == nil {
348新增: err = file.Sync()
349新增: }
350新增: if err != nil {
351新增: return errors.New("enrollment_pairing_not_saved")
352新增: }
353新增: if err = value.assertScope(); err != nil {
354新增: return err
355新增: }
356新增: if ctx.Err() != nil {
357新增: return errors.New("enrollment_cancelled")
358新增: }
359新增: if !value.admin.alive() {
360新增: return errors.New("enrollment_admin_exited")
361新增: }
362新增: completed = true
363新增: return nil
364新增:}
365新增:
366新增:func (value *windowsHostEnrollment) finalize(ctx context.Context) error {
367新增: if value.finalized {
368新增: return nil
369新增: }
370新增: ctx, cancel := context.WithTimeout(ctx, 35*time.Second)
371新增: defer cancel()
372新增: binding, err := LoadWindowsProfile(value.stage)
373新增: if err != nil || binding == nil || value.bindingValid(*binding) != nil || binding.GUIUserSID != value.guestSID || binding.NetworkPairingFile == "" {
374新增: return errors.New("enrollment_binding_not_ready")
375新增: }
376新增: for _, name := range []string{"pairing.dpapi", "packet.dpapi"} {
377新增: data, err := value.privateKey(filepath.Join(value.stage, name))
378新增: if err != nil {
379新增: return err
380新增: }
381新增: key, err := cryptHostEnrollment(data, value.options.VMID, value.guestSID, false)
382新增: if err != nil {
383新增: return err
384新增: }
385新增: valid := len(key) == 32
386新增: clear(key)
387新增: if !valid {
388新增: return errors.New("enrollment_binding_not_ready")
389新增: }
390新增: }
391新增: var ready bool
392新增: for ctx.Err() == nil {
393新增: if !value.admin.alive() {
394新增: return errors.New("enrollment_admin_exited")
395新增: }
396新增: if err = value.assertScope(); err != nil {
397新增: return err
398新增: }
399新增: request, requestErr := WindowsRelayCommand(ctx, value.stage, "status")
400新增: if requestErr != nil {
401新增: return errors.New("enrollment_relay_not_ready")
402新增: }
403新增: var output boundedEnrollmentOutput
404新增: request.Stdout = &output
405新增: request.Stderr = io.Discard
406新增: if request.Run() == nil {
407新增: var report struct {
408新增: Version int `json:"version"`
409新增: OS string `json:"os"`
410新增: VMID string `json:"vm_id"`
411新增: SID string `json:"gui_user_sid"`
412新增: Available bool `json:"available"`
413新增: Capabilities []string `json:"capabilities"`
414新增: Browser struct {
415新增: Installed bool `json:"installed"`
416新增: EditorInstalled bool `json:"editor_installed"`
417新增: } `json:"browser"`
418新增: Components map[string]struct {
419新增: Installed bool `json:"installed"`
420新增: Ready bool `json:"ready"`
421新增: } `json:"components"`
422新增: }
423新增: if json.Unmarshal(output.Bytes(), &report) == nil && report.Version == 1 && report.OS == "windows" && report.VMID == value.options.VMID.String() && report.SID == value.guestSID && report.Available && report.Browser.Installed && report.Browser.EditorInstalled {
424新增: ready = true
425新增: for _, name := range []string{"cli", "terminal", "project-mount", "desktop"} {
426新增: component := report.Components[name]
427新增: ready = ready && slices.Contains(report.Capabilities, name) && component.Installed && component.Ready
428新增: }
429新增: if ready {
430新增: break
431新增: }
432新增: }
433新增: }
434新增: select {
435新增: case <-ctx.Done():
436新增: case <-time.After(time.Second):
437新增: }
438新增: }
439新增: if !ready || ctx.Err() != nil || !value.admin.alive() {
440新增: return errors.New("enrollment_components_not_ready")
441新增: }
442新增: if err = value.assertScope(); err != nil {
443新增: return err
444新增: }
445新增: var state WindowsVMResourceState
446新增: if err = windowsHostManagerCall(ctx, value.options.VMID, "resources", 0, 0, &state); err != nil || state.State != "Running" {
447新增: return errors.New("enrollment_manager_not_ready")
448新增: }
449新增: if err = value.assertScope(); err != nil {
450新增: return err
451新增: }
452新增: if !value.admin.alive() || ctx.Err() != nil {
453新增: return errors.New("enrollment_cancelled")
454新增: }
455新增: if err = BindWindowsProfile(value.options.Profile, *binding); err != nil {
456新增: return errors.New("enrollment_profile_not_published")
457新增: }
458新增: value.finalized = true
459新增: return nil
460新增:}
461新增:
462新增:type boundedEnrollmentOutput struct{ bytes.Buffer }
463新增:
464新增:func (value *boundedEnrollmentOutput) Write(data []byte) (int, error) {
465新增: if value.Len()+len(data) > 64<<10 {
466新增: return 0, errors.New("enrollment_response_limit")
467新增: }
468新增: return value.Buffer.Write(data)
469新增:}
470新增:
471新增:func (value *windowsHostEnrollment) connection(ctx context.Context, conn net.Conn, cancel context.CancelFunc) {
472新增: defer conn.Close()
473新增: _ = conn.SetDeadline(time.Now().Add(10 * time.Second))
474新增: fd, ok := conn.(interface{ Fd() uintptr })
475新增: var pid uint32
476新增: if !ok || windows.GetNamedPipeClientProcessId(windows.Handle(fd.Fd()), &pid) != nil {
477新增: return
478新增: }
479新增: value.mu.Lock()
480新增: owner := pid == value.owner.pid && value.owner.alive()
481新增: admin := pid == value.admin.pid && value.admin.alive()
482新增: value.mu.Unlock()
483新增: challenge := make([]byte, 32)
484新增: if _, err := rand.Read(challenge); err != nil {
485新增: return
486新增: }
487新增: defer clear(challenge)
488新增: write := func(reply windowsHostEnrollmentReply) { reply.Version = 1; _ = json.NewEncoder(conn).Encode(reply) }
489新增: write(windowsHostEnrollmentReply{OK: owner || admin, Authorized: owner || admin, Challenge: base64.StdEncoding.EncodeToString(challenge)})
490新增: if !owner && !admin {
491新增: return
492新增: }
493新增: reader := bufio.NewReaderSize(conn, enrollmentWireLimit+1)
494新增: line, err := reader.ReadSlice('\n')
495新增: if err != nil || len(line) > enrollmentWireLimit {
496新增: return
497新增: }
498新增: var request windowsHostEnrollmentRequest
499新增: decoder := json.NewDecoder(bytes.NewReader(line))
500新增: decoder.DisallowUnknownFields()
501新增: if decoder.Decode(&request) != nil || decoder.Decode(new(any)) != io.EOF {
502新增: return
503新增: }
504新增: decoded, err := base64.StdEncoding.DecodeString(request.Challenge)
505新增: if err != nil || request.Version != 1 || request.VMID != value.options.VMID || subtle.ConstantTimeCompare(decoded, challenge) != 1 {
506新增: return
507新增: }
508新增: value.mu.Lock()
509新增: requestErr := request.validate(value.options.VMID, owner, value.guestSID)
510新增: value.mu.Unlock()
511新增: if requestErr != nil {
512新增: return
513新增: }
514新增: key := make([]byte, 32)
515新增: defer clear(key)
516新增: if request.Action == "deliver-gui" || request.Action == "deliver-packet" {
517新增: if !admin {
518新增: return
519新增: }
520新增: if _, err = io.ReadFull(reader, key); err != nil {
521新增: return
522新增: }
523新增: }
524新增: if reader.Buffered() != 0 {
525新增: return
526新增: }
527新增: _ = conn.SetDeadline(time.Now().Add(45 * time.Second))
528新增: operation, finish := context.WithCancel(ctx)
529新增: defer finish()
530新增: disconnected := make(chan struct{})
531新增: go func() { defer close(disconnected); var extra [1]byte; _, _ = conn.Read(extra[:]); finish() }()
532新增: defer func() { conn.Close(); <-disconnected }()
533新增: value.mu.Lock()
534新增: defer value.mu.Unlock()
535新增: if err = value.assertScope(); err != nil {
536新增: write(windowsHostEnrollmentReply{Error: err.Error()})
537新增: return
538新增: }
539新增: if owner {
540新增: switch request.Action {
541新增: case "ready":
542新增: case "allow-admin":
543新增: err = value.authorizeAdmin(request)
544新增: case "stop":
545新增: cancel()
546新增: default:
547新增: err = errors.New("enrollment_action_invalid")
548新增: }
549新增: } else if !value.admin.alive() {
550新增: err = errors.New("enrollment_admin_exited")
551新增: } else {
552新增: switch request.Action {
553新增: case "deliver-gui", "deliver-packet":
554新增: err = value.storeKey(operation, request.Action, request.GUIUserSID, key)
555新增: case "finalize":
556新增: if request.GUIUserSID != value.guestSID {
557新增: err = errors.New("enrollment_guest_changed")
558新增: } else {
559新增: err = value.finalize(operation)
560新增: }
561新增: default:
562新增: err = errors.New("enrollment_action_invalid")
563新增: }
564新增: }
565新增: if err != nil {
566新增: write(windowsHostEnrollmentReply{Error: "enrollment_not_completed"})
567新增: return
568新增: }
569新增: write(windowsHostEnrollmentReply{OK: true})
570新增:}
571新增:
572新增:func RunWindowsHostEnrollment(parent context.Context, options WindowsHostEnrollmentOptions) error {
573新增: value, err := newWindowsHostEnrollment(options)
574新增: if err != nil {
575新增: return err
576新增: }
577新增: defer windows.CloseHandle(value.owner.handle)
578新增: defer func() {
579新增: if value.admin.handle != 0 {
580新增: windows.CloseHandle(value.admin.handle)
581新增: }
582新增: }()
583新增: ctx, cancel := context.WithCancel(parent)
584新增: defer cancel()
585新增: listener, err := winio.ListenPipe(`\\.\pipe\`+options.Pipe, &winio.PipeConfig{SecurityDescriptor: "O:" + options.HostSID + "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;0x12019b;;;" + options.HostSID + ")", InputBufferSize: enrollmentWireLimit, OutputBufferSize: enrollmentWireLimit})
586新增: if err != nil {
587新增: return errors.New("enrollment_pipe_unavailable")
588新增: }
589新增: defer listener.Close()
590新增: var active sync.WaitGroup
591新增: var connections sync.Map
592新增: go func() {
593新增: ticker := time.NewTicker(200 * time.Millisecond)
594新增: defer ticker.Stop()
595新增: for {
596新增: select {
597新增: case <-ctx.Done():
598新增: listener.Close()
599新增: connections.Range(func(key, _ any) bool { key.(net.Conn).Close(); return true })
600新增: return
601新增: case <-ticker.C:
602新增: if !value.owner.alive() {
603新增: cancel()
604新增: }
605新增: }
606新增: }
607新增: }()
608新增: defer func() {
609新增: cancel()
610新增: listener.Close()
611新增: connections.Range(func(key, _ any) bool { key.(net.Conn).Close(); return true })
612新增: active.Wait()
613新增: }()
614新增: slots := make(chan struct{}, 4)
615新增: for {
616新增: conn, err := listener.Accept()
617新增: if err != nil {
618新增: if ctx.Err() != nil {
619新增: return nil
620新增: }
621新增: return errors.New("enrollment_pipe_unavailable")
622新增: }
623新增: select {
624新增: case slots <- struct{}{}:
625新增: default:
626新增: conn.Close()
627新增: continue
628新增: }
629新增: connections.Store(conn, struct{}{})
630新增: active.Add(1)
631新增: go func() {
632新增: defer active.Done()
633新增: defer func() { <-slots; connections.Delete(conn) }()
634新增: value.connection(ctx, conn, cancel)
635新增: }()
636新增: }
637新增:}
新增internal/guestos/windows_host_manager_acl_windows_test.go+61 −0看文件
@@ -0,0 +1,61 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "os"
7新增: "testing"
8新增:
9新增: "golang.org/x/sys/windows"
10新增:)
11新增:
12新增:// Native ACL fixtures contain only this test's temporary directory. They never
13新增:// change a real manager, VM, account, user group or installation directory.
14新增:func TestWindowsHostManagerProtectedDirectoryACL(t *testing.T) {
15新增: if os.Getenv("CAGE_TEST_WINDOWS_MANAGER_ACL") != "1" {
16新增: t.Skip("requires explicitly enabled administrator-owned ACL fixtures")
17新增: }
18新增: if !windows.GetCurrentProcessToken().IsElevated() {
19新增: t.Fatal("creating administrator-owned ACL fixtures requires an elevated test process")
20新增: }
21新增: user, err := windows.GetCurrentProcessToken().GetTokenUser()
22新增: if err != nil {
23新增: t.Fatal(err)
24新增: }
25新增: sid := user.User.Sid.String()
26新增: set := func(path, reader, mask string) {
27新增: t.Helper()
28新增: sd, err := windows.SecurityDescriptorFromString("O:BAG:SYD:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;" + mask + ";;;" + reader + ")")
29新增: if err != nil {
30新增: t.Fatal(err)
31新增: }
32新增: owner, _, _ := sd.Owner()
33新增: dacl, _, _ := sd.DACL()
34新增: if err := windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, owner, nil, dacl, nil); err != nil {
35新增: t.Fatal(err)
36新增: }
37新增: }
38新增: t.Run("shared_readers", func(t *testing.T) {
39新增: path := t.TempDir()
40新增: set(path, "S-1-5-32-545", "FRFX")
41新增: if err := managerSharedProtected(path, sid); err != nil {
42新增: t.Fatal("safe shared parent rejected", err)
43新增: }
44新增: if err := managerProtected(path, sid); err == nil {
45新增: t.Fatal("private per-VM authority permits unrelated readers")
46新增: }
47新增: })
48新增: t.Run("delete_child", func(t *testing.T) {
49新增: path := t.TempDir()
50新增: set(path, sid, "0x120040") // READ_CONTROL, SYNCHRONIZE, FILE_DELETE_CHILD.
51新增: if err := managerSharedProtected(path, sid); err == nil {
52新增: t.Fatal("shared parent accepts ordinary-user child replacement")
53新增: }
54新增: if err := managerProtected(path, sid); err == nil {
55新增: t.Fatal("private parent accepts ordinary-user child replacement")
56新增: }
57新增: if err := checkWindowsSystemOwnedObject(path); err == nil {
58新增: t.Fatal("client accepts ordinary-user child replacement")
59新增: }
60新增: })
61新增:}
新增internal/guestos/windows_host_manager_client_windows.go+232 −0看文件
@@ -0,0 +1,232 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "bufio"
7新增: "bytes"
8新增: "context"
9新增: "encoding/json"
10新增: "errors"
11新增: "fmt"
12新增: "io"
13新增: "net"
14新增: "os"
15新增: "path/filepath"
16新增: "runtime"
17新增: "strings"
18新增: "time"
19新增: "unsafe"
20新增:
21新增: "github.com/Microsoft/go-winio"
22新增: "github.com/google/uuid"
23新增: "golang.org/x/sys/windows"
24新增:)
25新增:
26新增:func windowsHostManagerCall(ctx context.Context, id uuid.UUID, operation string, memory, cpus int, result any) error {
27新增: request := windowsHostManagerRequest{Version: windowsHostManagerVersion, VMID: id, Operation: operation, MemoryGiB: memory, CPUs: cpus}
28新增: return windowsHostManagerRequestCall(ctx, request, result)
29新增:}
30新增:
31新增:func windowsHostManagerRequestCall(ctx context.Context, request windowsHostManagerRequest, result any) error {
32新增: id := request.VMID
33新增: if err := request.validate(); err != nil {
34新增: return errors.New("Windows 客机管理参数无效")
35新增: }
36新增: ctx, cancel := context.WithTimeout(ctx, 3*time.Minute)
37新增: defer cancel()
38新增: connect, finish := context.WithTimeout(ctx, 10*time.Second)
39新增: level := winio.PipeImpLevelIdentification
40新增: if request.Storage != nil && request.Storage.Action == "attach" {
41新增: // The verified service opens the destination using this caller's rights.
42新增: level = winio.PipeImpLevelImpersonation
43新增: }
44新增: connection, err := winio.DialPipeAccessImpLevel(connect, `\\.\pipe\Cage.HyperV.`+id.String(), 0x120003, level)
45新增: finish()
46新增: if err != nil {
47新增: if ctx.Err() != nil {
48新增: return ctx.Err()
49新增: }
50新增: return errors.New("Windows 系统管理助手尚未连接,请在 Cage 安装流程中完成系统授权或恢复助手;原虚拟机和数据已保留")
51新增: }
52新增: defer connection.Close()
53新增: stop := context.AfterFunc(ctx, func() { _ = connection.Close() })
54新增: defer stop()
55新增: if deadline, ok := ctx.Deadline(); ok {
56新增: _ = connection.SetDeadline(deadline)
57新增: }
58新增: if err := verifyWindowsHostManagerPeer(connection, id); err != nil {
59新增: return err
60新增: }
61新增: if err := json.NewEncoder(connection).Encode(request); err != nil {
62新增: return errors.New("Windows 系统管理请求没有完整送达")
63新增: }
64新增: line, err := bufio.NewReaderSize(connection, windowsHostManagerWireLimit).ReadSlice('\n')
65新增: if err != nil {
66新增: if ctx.Err() != nil {
67新增: return ctx.Err()
68新增: }
69新增: return errors.New("Windows 系统管理结果没有完整返回,现有环境已保留")
70新增: }
71新增: var response windowsHostManagerResponse
72新增: decoder := json.NewDecoder(bytes.NewReader(line))
73新增: decoder.DisallowUnknownFields()
74新增: if decoder.Decode(&response) != nil || decoder.Decode(new(any)) != io.EOF || response.Version != windowsHostManagerVersion || response.VMID != id {
75新增: return errors.New("Windows 系统管理响应身份或格式不匹配")
76新增: }
77新增: if err := verifyWindowsHostManagerPeer(connection, id); err != nil {
78新增: return err
79新增: }
80新增: if !response.OK || response.Error != "" {
81新增: if response.Error == "storage_pending" {
82新增: return errors.New("Windows 客机有待恢复的存储迁移,请重新打开原工作台完成恢复")
83新增: }
84新增: if response.Error == "vm_running" {
85新增: return errors.New("请等待 Windows 客机完整关机,再迁移环境存储")
86新增: }
87新增: if response.Error == "unauthorized" || response.Error == "permission_denied" {
88新增: return errors.New("当前系统用户没有这台 Cage 客机的管理授权")
89新增: }
90新增: if response.Error == "binding_mismatch" || response.Error == "layout_mismatch" || response.Error == "binding_invalid" {
91新增: return errors.New("Windows 客机的登记配置已变化,请核对原虚拟机;现有数据已保留")
92新增: }
93新增: return errors.New("Windows 系统管理操作未完成,请重试或在设置中导出诊断包;现有环境已保留")
94新增: }
95新增: if len(response.Result) == 0 || bytes.Equal(bytes.TrimSpace(response.Result), []byte("null")) || result == nil || json.Unmarshal(response.Result, result) != nil {
96新增: return errors.New("Windows 系统管理响应缺少实际读回结果")
97新增: }
98新增: return nil
99新增:}
100新增:
101新增:func verifyWindowsHostManagerPeer(connection net.Conn, id uuid.UUID) error {
102新增: f, ok := connection.(interface{ Fd() uintptr })
103新增: if !ok {
104新增: return errors.New("Windows 系统管理通道无法核验")
105新增: }
106新增: var pid uint32
107新增: if windows.GetNamedPipeServerProcessId(windows.Handle(f.Fd()), &pid) != nil || pid == 0 {
108新增: return errors.New("Windows 系统管理进程无法核验")
109新增: }
110新增: // Query the SCM with read-only rights. A normal user cannot open the
111新增: // LocalSystem process token; the protected service account and live PID
112新增: // provide the corresponding identity without requesting that privilege.
113新增: manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_CONNECT)
114新增: if err != nil {
115新增: return errors.New("Windows 系统管理服务身份无法读取")
116新增: }
117新增: defer windows.CloseServiceHandle(manager)
118新增: name, _ := windows.UTF16PtrFromString("CageHV-" + id.String())
119新增: service, err := windows.OpenService(manager, name, windows.SERVICE_QUERY_CONFIG|windows.SERVICE_QUERY_STATUS)
120新增: if err != nil {
121新增: return errors.New("Windows 系统管理服务未登记或当前用户不可读取")
122新增: }
123新增: defer windows.CloseServiceHandle(service)
124新增: var status windows.SERVICE_STATUS_PROCESS
125新增: var needed uint32
126新增: if windows.QueryServiceStatusEx(service, windows.SC_STATUS_PROCESS_INFO, (*byte)(unsafe.Pointer(&status)), uint32(unsafe.Sizeof(status)), &needed) != nil || status.ProcessId != pid || status.CurrentState != windows.SERVICE_RUNNING {
127新增: return errors.New("Windows 系统管理通道不属于当前已登记服务")
128新增: }
129新增: binaryPath, account, err := windowsHostServiceConfig(service)
130新增: if err != nil {
131新增: return errors.New("Windows 系统管理服务配置无法核验")
132新增: }
133新增: if !strings.EqualFold(account, "LocalSystem") && !strings.EqualFold(account, `NT AUTHORITY\SYSTEM`) {
134新增: return errors.New("Windows 系统管理服务未使用受限系统入口")
135新增: }
136新增: program, err := windows.KnownFolderPath(windows.FOLDERID_ProgramFiles, 0)
137新增: if err != nil {
138新增: return err
139新增: }
140新增: expected := filepath.Join(program, "Cage Host Manager", id.String(), "Cage.HyperVManager.exe")
141新增: data, err := windows.KnownFolderPath(windows.FOLDERID_ProgramData, 0)
142新增: if err != nil {
143新增: return err
144新增: }
145新增: binding := filepath.Join(data, "Cage", "HyperVManager", id.String(), "binding.json")
146新增: arguments, err := windows.DecomposeCommandLine(binaryPath)
147新增: if err != nil || len(arguments) != 4 || !strings.EqualFold(filepath.Clean(arguments[0]), filepath.Clean(expected)) || arguments[1] != "service" || arguments[2] != "--binding" || !strings.EqualFold(filepath.Clean(arguments[3]), filepath.Clean(binding)) {
148新增: return errors.New("Windows 系统管理程序不属于已登记的安装位置")
149新增: }
150新增: if err := checkWindowsSystemOwnedObject(binding); err != nil {
151新增: return err
152新增: }
153新增: for current := expected; !strings.EqualFold(current, program); current = filepath.Dir(current) {
154新增: if current == filepath.Dir(current) {
155新增: return fmt.Errorf("Windows 系统管理程序路径无效")
156新增: }
157新增: if err := checkWindowsSystemOwnedObject(current); err != nil {
158新增: return err
159新增: }
160新增: }
161新增: return nil
162新增:}
163新增:
164新增:func windowsHostServiceConfig(service windows.Handle) (string, string, error) {
165新增: // QUERY_SERVICE_CONFIG contains pointers into this native output buffer.
166新增: // A variable-sized allocation stays on the heap when later Go calls grow
167新增: // the stack; copy its strings before releasing the retained buffer.
168新增: size := uint32(1024)
169新增: for size <= windowsHostManagerWireLimit {
170新增: buffer := make([]byte, size)
171新增: config := (*windows.QUERY_SERVICE_CONFIG)(unsafe.Pointer(&buffer[0]))
172新增: var needed uint32
173新增: err := windows.QueryServiceConfig(service, config, size, &needed)
174新增: if err == nil {
175新增: binaryPath, account := windows.UTF16PtrToString(config.BinaryPathName), windows.UTF16PtrToString(config.ServiceStartName)
176新增: runtime.KeepAlive(buffer)
177新增: return binaryPath, account, nil
178新增: }
179新增: runtime.KeepAlive(buffer)
180新增: if !errors.Is(err, windows.ERROR_INSUFFICIENT_BUFFER) || needed <= size {
181新增: return "", "", err
182新增: }
183新增: size = needed
184新增: }
185新增: return "", "", errors.New("Windows service configuration exceeds limit")
186新增:}
187新增:
188新增:func checkWindowsSystemOwnedObject(path string) error {
189新增: info, err := os.Lstat(path)
190新增: if err != nil {
191新增: return errors.New("Windows 系统管理程序或目录不可读")
192新增: }
193新增: ptr, err := windows.UTF16PtrFromString(path)
194新增: if err != nil {
195新增: return err
196新增: }
197新增: attributes, err := windows.GetFileAttributes(ptr)
198新增: if err != nil || attributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 || !info.Mode().IsRegular() && !info.IsDir() {
199新增: return errors.New("Windows 系统管理程序不能经过目录链接")
200新增: }
201新增: sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION)
202新增: if err != nil {
203新增: return errors.New("Windows 系统管理程序权限不可读")
204新增: }
205新增: owner, _, err := sd.Owner()
206新增: if err != nil || owner == nil || !owner.IsWellKnown(windows.WinLocalSystemSid) && !owner.IsWellKnown(windows.WinBuiltinAdministratorsSid) {
207新增: return errors.New("Windows 系统管理程序未受系统权限保护")
208新增: }
209新增: acl, _, err := sd.DACL()
210新增: if err != nil || acl == nil || acl.AceCount == 0 {
211新增: return errors.New("Windows 系统管理程序没有访问限制")
212新增: }
213新增: const fileDeleteChild = 0x40 // FILE_DELETE_CHILD is absent from x/sys/windows.
214新增: const writes = windows.FILE_WRITE_DATA | windows.FILE_APPEND_DATA | windows.FILE_WRITE_EA | windows.FILE_WRITE_ATTRIBUTES | fileDeleteChild | windows.DELETE | windows.WRITE_DAC | windows.WRITE_OWNER | windows.GENERIC_WRITE | windows.GENERIC_ALL
215新增: for i := uint32(0); i < uint32(acl.AceCount); i++ {
216新增: var ace *windows.ACCESS_ALLOWED_ACE
217新增: if windows.GetAce(acl, i, &ace) != nil {
218新增: return errors.New("Windows 系统管理程序权限无法核验")
219新增: }
220新增: if ace.Header.AceType == windows.ACCESS_DENIED_ACE_TYPE {
221新增: continue
222新增: }
223新增: if ace.Header.AceType != windows.ACCESS_ALLOWED_ACE_TYPE {
224新增: return errors.New("Windows 系统管理程序含未支持的权限规则")
225新增: }
226新增: principal := (*windows.SID)(unsafe.Pointer(&ace.SidStart))
227新增: if ace.Mask&writes != 0 && !principal.IsWellKnown(windows.WinLocalSystemSid) && !principal.IsWellKnown(windows.WinBuiltinAdministratorsSid) {
228新增: return errors.New("Windows 系统管理程序可被普通用户修改")
229新增: }
230新增: }
231新增: return nil
232新增:}
新增internal/guestos/windows_host_manager_e2e_windows_test.go+138 −0看文件
@@ -0,0 +1,138 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "bufio"
7新增: "context"
8新增: "encoding/json"
9新增: "os"
10新增: "strings"
11新增: "testing"
12新增: "time"
13新增:
14新增: "github.com/Microsoft/go-winio"
15新增: "github.com/google/uuid"
16新增: "golang.org/x/sys/windows"
17新增:)
18新增:
19新增:// This test only reads the already registered VM. It must run in the ordinary
20新增:// desktop user's token so direct Hyper-V administrator access cannot mask a
21新增:// broken manager boundary.
22新增:func TestWindowsHostManagerOrdinaryRead(t *testing.T) {
23新增: idText := os.Getenv("CAGE_TEST_WINDOWS_MANAGER_VM")
24新增: if idText == "" {
25新增: t.Skip("requires the installed fixed-VM manager and ordinary host session")
26新增: }
27新增: id, err := uuid.Parse(idText)
28新增: if err != nil {
29新增: t.Fatal("invalid test VM")
30新增: }
31新增: token := windows.GetCurrentProcessToken()
32新增: if token.IsElevated() {
33新增: t.Fatal("this acceptance test must use the ordinary desktop token")
34新增: }
35新增: admins, _ := windows.StringToSid("S-1-5-32-578")
36新增: member, err := token.IsMember(admins)
37新增: if err != nil || member {
38新增: t.Fatal("ordinary host must not receive Hyper-V Administrators membership")
39新增: }
40新增: binding, err := LoadWindowsHostManagerBinding(WindowsHostManagerBindingPath(id))
41新增: if err != nil {
42新增: t.Fatal(err)
43新增: }
44新增: user, err := token.GetTokenUser()
45新增: if err != nil || user.User.Sid.String() != binding.HostSID {
46新增: t.Fatal("acceptance token differs from protected manager host identity")
47新增: }
48新增: for _, path := range []string{WindowsHostManagerBindingPath(id), WindowsHostManagerExecutablePath(id)} {
49新增: name, _ := windows.UTF16PtrFromString(path)
50新增: handle, err := windows.CreateFile(name, windows.FILE_WRITE_DATA|windows.WRITE_DAC, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, 0, 0)
51新增: if err == nil {
52新增: windows.CloseHandle(handle)
53新增: t.Fatal("ordinary caller can alter manager code or authority")
54新增: }
55新增: if err != windows.ERROR_ACCESS_DENIED {
56新增: t.Fatal("manager write protection was not proven by access denial", err)
57新增: }
58新增: }
59新增: scm, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_CONNECT)
60新增: if err != nil {
61新增: t.Fatal(err)
62新增: }
63新增: defer windows.CloseServiceHandle(scm)
64新增: serviceName, _ := windows.UTF16PtrFromString(WindowsHostManagerServiceName(id))
65新增: service, err := windows.OpenService(scm, serviceName, windows.SERVICE_QUERY_CONFIG|windows.SERVICE_QUERY_STATUS|windows.SERVICE_START)
66新增: if err != nil {
67新增: t.Fatal("ordinary host cannot query or restore its fixed helper", err)
68新增: }
69新增: windows.CloseServiceHandle(service)
70新增: service, err = windows.OpenService(scm, serviceName, windows.SERVICE_CHANGE_CONFIG|windows.WRITE_DAC)
71新增: if err == nil {
72新增: windows.CloseServiceHandle(service)
73新增: t.Fatal("ordinary host can replace its SYSTEM service configuration")
74新增: }
75新增: if err != windows.ERROR_ACCESS_DENIED {
76新增: t.Fatal("service configuration write denial was not proven", err)
77新增: }
78新增: ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
79新增: defer cancel()
80新增: var inspected HyperVInspection
81新增: if err := windowsHostManagerCall(ctx, id, "inspect", 0, 0, &inspected); err != nil {
82新增: t.Fatal(err)
83新增: }
84新增: if inspected.Lookup != "found" || inspected.VMID != id.String() || inspected.VM == nil || inspected.VM.NetworkAdapterCount != 0 || inspected.VM.Generation != 2 || !inspected.VM.SecureBoot || !inspected.VM.VirtualTPM {
85新增: t.Fatal("manager did not return the registered offline-network VM layout")
86新增: }
87新增: public, err := InspectHyperV(ctx, id)
88新增: if err != nil || public.Lookup != "found" || public.VMID != id.String() || public.VM == nil || public.VM.State != inspected.VM.State {
89新增: t.Fatal("ordinary public inspection did not reach the authenticated fixed-VM manager", err)
90新增: }
91新增: var resources WindowsVMResourceState
92新增: if err := windowsHostManagerCall(ctx, id, "resources", 0, 0, &resources); err != nil {
93新增: t.Fatal(err)
94新增: }
95新增: if resources.State != inspected.VM.State || resources.CPUs <= 0 || resources.MemoryStartup < 4<<30 {
96新增: t.Fatal("manager did not return actual fixed-VM resources")
97新增: }
98新增: t.Logf("ordinary token accepted; VM state=%s, no NIC, CPU=%d, memory=%d GiB", inspected.VM.State, resources.CPUs, resources.MemoryStartup>>30)
99新增:
100新增: request := func(t *testing.T, body string, expected string) {
101新增: t.Helper()
102新增: conn, err := winio.DialPipeAccessImpLevel(ctx, `\\.\pipe\Cage.HyperV.`+id.String(), 0x120003, winio.PipeImpLevelIdentification)
103新增: if err != nil {
104新增: t.Fatal(err)
105新增: }
106新增: defer conn.Close()
107新增: _ = conn.SetDeadline(time.Now().Add(10 * time.Second))
108新增: if err := verifyWindowsHostManagerPeer(conn, id); err != nil {
109新增: t.Fatal(err)
110新增: }
111新增: if _, err := conn.Write([]byte(body)); err != nil {
112新增: t.Fatal(err)
113新增: }
114新增: line, err := bufio.NewReader(conn).ReadBytes('\n')
115新增: if err != nil {
116新增: t.Fatal(err)
117新增: }
118新增: var response windowsHostManagerResponse
119新增: if json.Unmarshal(line, &response) != nil || response.OK || response.Error != expected || response.VMID != id || response.Version != windowsHostManagerVersion || len(response.Result) != 0 {
120新增: t.Fatalf("unsafe or unexpected rejection: %s", line)
121新增: }
122新增: }
123新增: for _, item := range []struct{ name, body, code string }{
124新增: {"wrong_vm", `{"version":1,"vm_id":"` + uuid.NewString() + `","operation":"inspect"}` + "\n", "invalid_request"},
125新增: {"unknown_operation", `{"version":1,"vm_id":"` + id.String() + `","operation":"execute"}` + "\n", "invalid_request"},
126新增: {"unknown_field", `{"version":1,"vm_id":"` + id.String() + `","operation":"inspect","command":"noop"}` + "\n", "invalid_request"},
127新增: {"resource_bounds", `{"version":1,"vm_id":"` + id.String() + `","operation":"resources","memory_gib":1025,"cpus":1}` + "\n", "invalid_request"},
128新增: {"oversize", strings.Repeat("x", windowsHostManagerWireLimit+1) + "\n", "invalid_request"},
129新增: {"extra_json", `{"version":1,"vm_id":"` + id.String() + `","operation":"inspect"} {}` + "\n", "invalid_request"},
130新增: } {
131新增: t.Run(item.name, func(t *testing.T) { request(t, item.body, item.code) })
132新增: }
133新增: // Invalid clients must not poison later reads or stop the existing VM.
134新增: var after HyperVInspection
135新增: if err := windowsHostManagerCall(ctx, id, "inspect", 0, 0, &after); err != nil || after.VM == nil || after.VM.State != inspected.VM.State {
136新增: t.Fatal("rejected requests damaged the manager or VM state", err)
137新增: }
138新增:}
新增internal/guestos/windows_host_manager_server_windows.go+474 −0看文件
@@ -0,0 +1,474 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "bufio"
7新增: "bytes"
8新增: "context"
9新增: "encoding/json"
10新增: "errors"
11新增: "fmt"
12新增: "io"
13新增: "net"
14新增: "os"
15新增: "path/filepath"
16新增: "runtime"
17新增: "strings"
18新增: "sync"
19新增: "time"
20新增: "unsafe"
21新增:
22新增: "github.com/Microsoft/go-winio"
23新增: "github.com/google/uuid"
24新增: "golang.org/x/sys/windows"
25新增:
26新增: "github.com/sylvinus/agent-vm/internal/paths"
27新增:)
28新增:
29新增:// WindowsHostManagerBinding is installed by an administrator. The service never
30新增:// takes its authority from a user's workbench profile or a pipe request.
31新增:type WindowsHostManagerBinding struct {
32新增: Version int `json:"version"`
33新增: VMID uuid.UUID `json:"vm_id"`
34新增: HostSID string `json:"host_sid"`
35新增: DiskPath string `json:"disk_path"`
36新增: DiskVolume uint32 `json:"disk_volume"`
37新增: DiskFileID uint64 `json:"disk_file_id"`
38新增:}
39新增:
40新增:func WindowsHostManagerServiceName(id uuid.UUID) string { return "CageHV-" + id.String() }
41新增:
42新增:func managerKnownFolder(id *windows.KNOWNFOLDERID) string {
43新增: p, err := windows.KnownFolderPath(id, 0)
44新增: if err != nil {
45新增: return ""
46新增: }
47新增: return p
48新增:}
49新增:
50新增:func WindowsHostManagerBindingPath(id uuid.UUID) string {
51新增: return filepath.Join(managerKnownFolder(windows.FOLDERID_ProgramData), "Cage", "HyperVManager", id.String(), "binding.json")
52新增:}
53新增:
54新增:func WindowsHostManagerExecutablePath(id uuid.UUID) string {
55新增: return filepath.Join(managerKnownFolder(windows.FOLDERID_ProgramFiles), "Cage Host Manager", id.String(), "Cage.HyperVManager.exe")
56新增:}
57新增:
58新增:func managerProtected(path, hostSID string) error {
59新增: return managerProtectedAccess(path, hostSID, false)
60新增:}
61新增:
62新增:func managerSharedProtected(path, hostSID string) error {
63新增: return managerProtectedAccess(path, hostSID, true)
64新增:}
65新增:
66新增:func managerProtectedAccess(path, hostSID string, shared bool) error {
67新增: for p := path; p != filepath.Dir(p); p = filepath.Dir(p) {
68新增: name, err := windows.UTF16PtrFromString(p)
69新增: if err != nil {
70新增: return errors.New("binding_invalid")
71新增: }
72新增: attributes, err := windows.GetFileAttributes(name)
73新增: if err != nil || attributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 {
74新增: return errors.New("binding_invalid")
75新增: }
76新增: }
77新增: sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION)
78新增: if err != nil {
79新增: return errors.New("binding_invalid")
80新增: }
81新增: owner, _, err := sd.Owner()
82新增: if err != nil || owner == nil || !(owner.IsWellKnown(windows.WinLocalSystemSid) || owner.IsWellKnown(windows.WinBuiltinAdministratorsSid)) {
83新增: return errors.New("binding_invalid")
84新增: }
85新增: control, _, err := sd.Control()
86新增: if err != nil || control&windows.SE_DACL_PROTECTED == 0 {
87新增: return errors.New("binding_invalid")
88新增: }
89新增: acl, _, err := sd.DACL()
90新增: if err != nil || acl == nil || acl.AceCount == 0 {
91新增: return errors.New("binding_invalid")
92新增: }
93新增: for index := uint32(0); index < uint32(acl.AceCount); index++ {
94新增: var ace *windows.ACCESS_ALLOWED_ACE
95新增: if windows.GetAce(acl, index, &ace) != nil || ace.Header.AceType != windows.ACCESS_ALLOWED_ACE_TYPE {
96新增: return errors.New("binding_invalid")
97新增: }
98新增: sid := (*windows.SID)(unsafe.Pointer(&ace.SidStart))
99新增: if sid.IsWellKnown(windows.WinLocalSystemSid) || sid.IsWellKnown(windows.WinBuiltinAdministratorsSid) {
100新增: continue
101新增: }
102新增: const deleteChild = 0x40 // FILE_DELETE_CHILD is absent from x/sys/windows.
103新增: const modify = windows.FILE_WRITE_DATA | windows.FILE_APPEND_DATA | windows.FILE_WRITE_EA | windows.FILE_WRITE_ATTRIBUTES | deleteChild | windows.DELETE | windows.WRITE_DAC | windows.WRITE_OWNER | windows.GENERIC_WRITE | windows.GENERIC_ALL
104新增: if (!shared && sid.String() != hostSID) || ace.Mask&modify != 0 {
105新增: return errors.New("binding_invalid")
106新增: }
107新增: }
108新增: return nil
109新增:}
110新增:
111新增:func LoadWindowsHostManagerBinding(path string) (WindowsHostManagerBinding, error) {
112新增: var binding WindowsHostManagerBinding
113新增: file, err := os.Open(path)
114新增: if err != nil {
115新增: return binding, errors.New("binding_invalid")
116新增: }
117新增: defer file.Close()
118新增: info, err := file.Stat()
119新增: if err != nil || !info.Mode().IsRegular() || info.Size() > windowsHostManagerWireLimit {
120新增: return binding, errors.New("binding_invalid")
121新增: }
122新增: decoder := json.NewDecoder(io.LimitReader(file, windowsHostManagerWireLimit+1))
123新增: decoder.DisallowUnknownFields()
124新增: if decoder.Decode(&binding) != nil || decoder.Decode(new(any)) != io.EOF || binding.Version != windowsHostManagerVersion || binding.VMID == uuid.Nil || binding.DiskFileID == 0 || binding.DiskVolume == 0 || !filepath.IsAbs(binding.DiskPath) || strings.HasPrefix(binding.DiskPath, `\\`) || !strings.EqualFold(filepath.Ext(binding.DiskPath), ".vhdx") {
125新增: return binding, errors.New("binding_invalid")
126新增: }
127新增: sid, err := windows.StringToSid(binding.HostSID)
128新增: if err != nil || !(strings.HasPrefix(sid.String(), "S-1-5-21-") || strings.HasPrefix(sid.String(), "S-1-12-1-")) || !strings.EqualFold(filepath.Clean(path), WindowsHostManagerBindingPath(binding.VMID)) {
129新增: return binding, errors.New("binding_invalid")
130新增: }
131新增: if err = managerProtected(path, binding.HostSID); err != nil {
132新增: return binding, err
133新增: }
134新增: if err = managerProtected(filepath.Dir(path), binding.HostSID); err != nil {
135新增: return binding, err
136新增: }
137新增: if err = managerSharedProtected(filepath.Dir(filepath.Dir(path)), binding.HostSID); err != nil {
138新增: return binding, err
139新增: }
140新增: if err = managerSharedProtected(filepath.Dir(filepath.Dir(filepath.Dir(path))), binding.HostSID); err != nil {
141新增: return binding, err
142新增: }
143新增: return binding, nil
144新增:}
145新增:
146新增:func managerDiskIdentity(path string) (uint32, uint64, error) {
147新增: name, err := windows.UTF16PtrFromString(path)
148新增: if err != nil {
149新增: return 0, 0, errors.New("vm_changed")
150新增: }
151新增: handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0)
152新增: if err != nil {
153新增: return 0, 0, errors.New("vm_changed")
154新增: }
155新增: defer windows.CloseHandle(handle)
156新增: var info windows.ByHandleFileInformation
157新增: if windows.GetFileInformationByHandle(handle, &info) != nil || info.FileAttributes&(windows.FILE_ATTRIBUTE_DIRECTORY|windows.FILE_ATTRIBUTE_REPARSE_POINT) != 0 {
158新增: return 0, 0, errors.New("vm_changed")
159新增: }
160新增: return info.VolumeSerialNumber, uint64(info.FileIndexHigh)<<32 | uint64(info.FileIndexLow), nil
161新增:}
162新增:
163新增:func managerVMDisk(ctx context.Context, id uuid.UUID) (string, error) {
164新增: script := fmt.Sprintf("$ErrorActionPreference='Stop';$v=Get-VM -Id ([guid]'%s');$d=@(Get-VMHardDiskDrive -VM $v);if($d.Count -ne 1){throw 'bound_disk_invalid'};[pscustomobject]@{path=$d[0].Path}|ConvertTo-Json -Compress", id.String())
165新增: cmd, err := systemPowerShellQuery(ctx, script)
166新增: if err != nil {
167新增: return "", errors.New("vm_changed")
168新增: }
169新增: data, err := cmd.Output()
170新增: if err != nil || len(data) > 16384 {
171新增: return "", errors.New("vm_changed")
172新增: }
173新增: var disk struct {
174新增: Path string `json:"path"`
175新增: }
176新增: if json.Unmarshal(data, &disk) != nil {
177新增: return "", errors.New("vm_changed")
178新增: }
179新增: return disk.Path, nil
180新增:}
181新增:
182新增:func managerValidateVM(ctx context.Context, binding WindowsHostManagerBinding) (HyperVInspection, error) {
183新增: state, err := inspectHyperVNative(ctx, binding.VMID)
184新增: if err != nil || state.Lookup != "found" || state.VM == nil || state.VM.Generation != 2 || !state.VM.SecureBoot || !state.VM.VirtualTPM || state.VM.NetworkAdapterCount != 0 || state.VM.DiskCount != 1 || state.VM.SingleLocalVHDX == nil || !*state.VM.SingleLocalVHDX {
185新增: return state, errors.New("vm_changed")
186新增: }
187新增: disk, err := managerVMDisk(ctx, binding.VMID)
188新增: if err != nil {
189新增: return state, err
190新增: }
191新增: real, err := paths.Resolve(disk)
192新增: if err != nil || !strings.EqualFold(real, binding.DiskPath) {
193新增: return state, errors.New("vm_changed")
194新增: }
195新增: volume, id, err := managerDiskIdentity(real)
196新增: if err != nil || volume != binding.DiskVolume || id != binding.DiskFileID {
197新增: return state, errors.New("vm_changed")
198新增: }
199新增: return state, nil
200新增:}
201新增:
202新增:func PrepareWindowsHostManagerBinding(ctx context.Context, id uuid.UUID, hostSID string) (WindowsHostManagerBinding, error) {
203新增: var binding WindowsHostManagerBinding
204新增: token := windows.GetCurrentProcessToken()
205新增: host, err := windows.StringToSid(hostSID)
206新增: if err != nil || !token.IsElevated() || !(strings.HasPrefix(host.String(), "S-1-5-21-") || strings.HasPrefix(host.String(), "S-1-12-1-")) {
207新增: return binding, errors.New("installation_requires_administrator")
208新增: }
209新增: state, err := inspectHyperVNative(ctx, id)
210新增: if err != nil || state.Lookup != "found" || state.VM == nil || state.VM.Generation != 2 || !state.VM.SecureBoot || !state.VM.VirtualTPM || state.VM.NetworkAdapterCount != 0 || state.VM.DiskCount != 1 {
211新增: return binding, errors.New("vm_changed")
212新增: }
213新增: disk, err := managerVMDisk(ctx, id)
214新增: if err != nil {
215新增: return binding, err
216新增: }
217新增: real, err := paths.Resolve(disk)
218新增: if err != nil || strings.HasPrefix(real, `\\`) || !strings.EqualFold(filepath.Ext(real), ".vhdx") {
219新增: return binding, errors.New("vm_changed")
220新增: }
221新增: volume, fileID, err := managerDiskIdentity(real)
222新增: if err != nil {
223新增: return binding, err
224新增: }
225新增: return WindowsHostManagerBinding{Version: windowsHostManagerVersion, VMID: id, HostSID: hostSID, DiskPath: real, DiskVolume: volume, DiskFileID: fileID}, nil
226新增:}
227新增:
228新增:func managerClientSID(conn net.Conn) (string, error) {
229新增: file, ok := conn.(interface{ Fd() uintptr })
230新增: if !ok {
231新增: return "", errors.New("unauthorized")
232新增: }
233新增: var pid uint32
234新增: if windows.GetNamedPipeClientProcessId(windows.Handle(file.Fd()), &pid) != nil || pid == 0 {
235新增: return "", errors.New("unauthorized")
236新增: }
237新增: process, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid)
238新增: if err != nil {
239新增: return "", errors.New("unauthorized")
240新增: }
241新增: defer windows.CloseHandle(process)
242新增: var token windows.Token
243新增: if windows.OpenProcessToken(process, windows.TOKEN_QUERY, &token) != nil {
244新增: return "", errors.New("unauthorized")
245新增: }
246新增: defer token.Close()
247新增: user, err := token.GetTokenUser()
248新增: if err != nil {
249新增: return "", errors.New("unauthorized")
250新增: }
251新增: return user.User.Sid.String(), nil
252新增:}
253新增:
254新增:type windowsHostManagerServer struct {
255新增: binding WindowsHostManagerBinding
256新增: mutate sync.RWMutex
257新增:}
258新增:
259新增:func managerHostMemoryGiB() int {
260新增: var memory struct {
261新增: Length, Load uint32
262新增: TotalPhysical, AvailablePhysical, TotalPage, AvailablePage, TotalVirtual, AvailableVirtual, AvailableExtended uint64
263新增: }
264新增: memory.Length = uint32(unsafe.Sizeof(memory))
265新增: result, _, _ := windows.NewLazySystemDLL("kernel32.dll").NewProc("GlobalMemoryStatusEx").Call(uintptr(unsafe.Pointer(&memory)))
266新增: if result == 0 {
267新增: return 0
268新增: }
269新增: return int(memory.TotalPhysical >> 30)
270新增:}
271新增:
272新增:func (server *windowsHostManagerServer) request(ctx context.Context, request windowsHostManagerRequest, conn net.Conn) (any, error) {
273新增: if request.validate() != nil || request.VMID != server.binding.VMID {
274新增: return nil, errors.New("invalid_request")
275新增: }
276新增: if request.Operation == "storage" || request.Operation == "start" || request.Operation == "shutdown" || request.Operation == "resources" && request.CPUs != 0 {
277新增: server.mutate.Lock()
278新增: defer server.mutate.Unlock()
279新增: } else {
280新增: server.mutate.RLock()
281新增: defer server.mutate.RUnlock()
282新增: }
283新增: journal, err := server.loadStorageJournal()
284新增: if err != nil {
285新增: return nil, err
286新增: }
287新增: if request.Storage != nil {
288新增: return server.storageRequest(ctx, *request.Storage, journal, conn)
289新增: }
290新增: if journal != nil && journal.Phase == "pending" {
291新增: return nil, errors.New("storage_pending")
292新增: }
293新增: state, err := managerValidateVM(ctx, server.binding)
294新增: if err != nil {
295新增: return nil, err
296新增: }
297新增: name, err := windows.UTF16PtrFromString(server.binding.DiskPath)
298新增: if err != nil {
299新增: return nil, errors.New("vm_changed")
300新增: }
301新增: // Hold the verified inode across the operation. A same-user caller cannot
302新增: // replace the VHDX path after validation while the SYSTEM operation runs.
303新增: lockedDisk, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0)
304新增: if err != nil {
305新增: return nil, errors.New("vm_changed")
306新增: }
307新增: defer windows.CloseHandle(lockedDisk)
308新增: var pinned windows.ByHandleFileInformation
309新增: if windows.GetFileInformationByHandle(lockedDisk, &pinned) != nil || pinned.VolumeSerialNumber != server.binding.DiskVolume || uint64(pinned.FileIndexHigh)<<32|uint64(pinned.FileIndexLow) != server.binding.DiskFileID {
310新增: return nil, errors.New("vm_changed")
311新增: }
312新增: switch request.Operation {
313新增: case "inspect":
314新增: return state, nil
315新增: case "resources":
316新增: if request.CPUs != 0 {
317新增: maxMemory, maxCPUs := WindowsVMResourceCeiling(managerHostMemoryGiB(), runtime.NumCPU())
318新增: if request.CPUs > maxCPUs || request.MemoryGiB > maxMemory {
319新增: return nil, errors.New("resources_out_of_bounds")
320新增: }
321新增: }
322新增: return windowsVMResourcesNative(ctx, server.binding.VMID, request.MemoryGiB, request.CPUs)
323新增: case "start", "shutdown":
324新增: action := "start"
325新增: if request.Operation == "shutdown" {
326新增: action = "stop"
327新增: }
328新增: if err := windowsVMActionNative(ctx, server.binding.VMID, action); err != nil {
329新增: return nil, errors.New("operation_failed")
330新增: }
331新增: if _, err = managerValidateVM(ctx, server.binding); err != nil {
332新增: return nil, err
333新增: }
334新增: return windowsVMResourcesNative(ctx, server.binding.VMID, 0, 0)
335新增: }
336新增: return nil, errors.New("invalid_operation")
337新增:}
338新增:
339新增:func (server *windowsHostManagerServer) connection(ctx context.Context, conn net.Conn) {
340新增: defer conn.Close()
341新增: response := windowsHostManagerResponse{Version: windowsHostManagerVersion, VMID: server.binding.VMID}
342新增: write := func() {
343新增: conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
344新增: _ = json.NewEncoder(conn).Encode(response)
345新增: }
346新增: sid, err := managerClientSID(conn)
347新增: if err != nil || sid != server.binding.HostSID {
348新增: response.Error = "unauthorized"
349新增: write()
350新增: return
351新增: }
352新增: conn.SetReadDeadline(time.Now().Add(10 * time.Second))
353新增: reader := bufio.NewReaderSize(conn, windowsHostManagerWireLimit+1)
354新增: line, err := reader.ReadSlice('\n')
355新增: if err != nil || len(line) > windowsHostManagerWireLimit || reader.Buffered() != 0 {
356新增: response.Error = "invalid_request"
357新增: write()
358新增: return
359新增: }
360新增: var request windowsHostManagerRequest
361新增: decoder := json.NewDecoder(bytes.NewReader(line))
362新增: decoder.DisallowUnknownFields()
363新增: if decoder.Decode(&request) != nil || decoder.Decode(new(any)) != io.EOF {
364新增: response.Error = "invalid_request"
365新增: write()
366新增: return
367新增: }
368新增: conn.SetReadDeadline(time.Time{})
369新增: deadline := time.Minute
370新增: if request.Storage != nil {
371新增: deadline = 3 * time.Minute
372新增: }
373新增: operation, cancel := context.WithTimeout(ctx, deadline)
374新增: defer cancel()
375新增: // One request per pipe. A client disconnect or extra command cancels work.
376新增: disconnected := make(chan struct{})
377新增: go func() { defer close(disconnected); var extra [1]byte; _, _ = conn.Read(extra[:]); cancel() }()
378新增: result, err := server.request(operation, request, conn)
379新增: if err != nil {
380新增: response.Error = "operation_failed"
381新增: for _, code := range []string{"invalid_request", "invalid_operation", "vm_changed", "resources_out_of_bounds", "storage_pending", "vm_running"} {
382新增: if err.Error() == code {
383新增: response.Error = code
384新增: }
385新增: }
386新增: if operation.Err() != nil {
387新增: response.Error = "cancelled"
388新增: }
389新增: } else {
390新增: response.Result, err = json.Marshal(result)
391新增: response.OK = err == nil
392新增: if err != nil {
393新增: response.Error = "operation_failed"
394新增: }
395新增: }
396新增: write()
397新增: conn.Close()
398新增: <-disconnected
399新增:}
400新增:
401新增:func ServeWindowsHostManager(parent context.Context, path string) error {
402新增: return serveWindowsHostManager(parent, path, nil)
403新增:}
404新增:
405新增:func serveWindowsHostManager(parent context.Context, path string, ready chan<- struct{}) error {
406新增: ctx, cancel := context.WithCancel(parent)
407新增: defer cancel()
408新增: user, err := windows.GetCurrentProcessToken().GetTokenUser()
409新增: if err != nil || !user.User.Sid.IsWellKnown(windows.WinLocalSystemSid) {
410新增: return errors.New("service_requires_system")
411新增: }
412新增: binding, err := LoadWindowsHostManagerBinding(path)
413新增: if err != nil {
414新增: return err
415新增: }
416新增: exe, err := os.Executable()
417新增: if err != nil || !strings.EqualFold(exe, WindowsHostManagerExecutablePath(binding.VMID)) {
418新增: return errors.New("binding_invalid")
419新增: }
420新增: if err = managerProtected(exe, binding.HostSID); err != nil {
421新增: return err
422新增: }
423新增: if err = managerProtected(filepath.Dir(exe), binding.HostSID); err != nil {
424新增: return err
425新增: }
426新增: if err = managerSharedProtected(filepath.Dir(filepath.Dir(exe)), binding.HostSID); err != nil {
427新增: return err
428新增: }
429新增: server := windowsHostManagerServer{binding: binding}
430新增: listener, err := winio.ListenPipe(`\\.\pipe\Cage.HyperV.`+binding.VMID.String(), &winio.PipeConfig{SecurityDescriptor: "O:SYG:SYD:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;0x12019b;;;" + binding.HostSID + ")", InputBufferSize: windowsHostManagerWireLimit, OutputBufferSize: windowsHostManagerWireLimit})
431新增: if err != nil {
432新增: return errors.New("service_pipe_unavailable")
433新增: }
434新增: defer listener.Close()
435新增: if ready != nil {
436新增: close(ready)
437新增: }
438新增: var active sync.WaitGroup
439新增: var connections sync.Map
440新增: go func() {
441新增: <-ctx.Done()
442新增: listener.Close()
443新增: connections.Range(func(key, _ any) bool { key.(net.Conn).Close(); return true })
444新增: }()
445新增: slots := make(chan struct{}, 16)
446新增: defer func() {
447新增: cancel()
448新增: listener.Close()
449新增: connections.Range(func(key, _ any) bool { key.(net.Conn).Close(); return true })
450新增: active.Wait()
451新增: }()
452新增: for {
453新增: conn, err := listener.Accept()
454新增: if err != nil {
455新增: if ctx.Err() != nil {
456新增: return nil
457新增: }
458新增: return errors.New("service_pipe_unavailable")
459新增: }
460新增: select {
461新增: case slots <- struct{}{}:
462新增: default:
463新增: conn.Close()
464新增: continue
465新增: }
466新增: connections.Store(conn, struct{}{})
467新增: active.Add(1)
468新增: go func() {
469新增: defer active.Done()
470新增: defer func() { <-slots; connections.Delete(conn) }()
471新增: server.connection(ctx, conn)
472新增: }()
473新增: }
474新增:}
新增internal/guestos/windows_host_manager_service_windows.go+60 −0看文件
@@ -0,0 +1,60 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "context"
7新增: "errors"
8新增: "golang.org/x/sys/windows/svc"
9新增:)
10新增:
11新增:type windowsHostManagerHandler struct{ bindingPath string }
12新增:
13新增:func (handler windowsHostManagerHandler) Execute(_ []string, requests <-chan svc.ChangeRequest, status chan<- svc.Status) (bool, uint32) {
14新增: status <- svc.Status{State: svc.StartPending, WaitHint: 30000}
15新增: ctx, cancel := context.WithCancel(context.Background())
16新增: defer cancel()
17新增: done := make(chan error, 1)
18新增: ready := make(chan struct{})
19新增: go func() { done <- serveWindowsHostManager(ctx, handler.bindingPath, ready) }()
20新增: select {
21新增: case <-ready:
22新增: case <-done:
23新增: return true, 1
24新增: }
25新增: status <- svc.Status{State: svc.Running, Accepts: svc.AcceptStop | svc.AcceptShutdown}
26新增: for {
27新增: select {
28新增: case err := <-done:
29新增: if err != nil {
30新增: return true, 1
31新增: }
32新增: return false, 0
33新增: case request := <-requests:
34新增: switch request.Cmd {
35新增: case svc.Interrogate:
36新增: status <- request.CurrentStatus
37新增: case svc.Stop, svc.Shutdown:
38新增: status <- svc.Status{State: svc.StopPending}
39新增: cancel()
40新增: err := <-done
41新增: if err != nil {
42新增: return true, 1
43新增: }
44新增: return false, 0
45新增: }
46新增: }
47新增: }
48新增:}
49新增:
50新增:func RunWindowsHostManagerService(path string) error {
51新增: service, err := svc.IsWindowsService()
52新增: if err != nil || !service {
53新增: return errors.New("manager_requires_scm")
54新增: }
55新增: binding, err := LoadWindowsHostManagerBinding(path)
56新增: if err != nil {
57新增: return err
58新增: }
59新增: return svc.Run(WindowsHostManagerServiceName(binding.VMID), windowsHostManagerHandler{bindingPath: path})
60新增:}
新增internal/guestos/windows_host_manager_wire.go+117 −0看文件
@@ -0,0 +1,117 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "errors"
6新增: "strings"
7新增:
8新增: "github.com/google/uuid"
9新增:)
10新增:
11新增:const windowsHostManagerVersion = 1
12新增:const windowsHostManagerWireLimit = 64 << 10
13新增:
14新增:type windowsHostManagerRequest struct {
15新增: Version int `json:"version"`
16新增: VMID uuid.UUID `json:"vm_id"`
17新增: Operation string `json:"operation"`
18新增: MemoryGiB int `json:"memory_gib,omitempty"`
19新增: CPUs int `json:"cpus,omitempty"`
20新增: Storage *windowsHostStorageRequest `json:"storage,omitempty"`
21新增:}
22新增:
23新增:type windowsStorageDisk struct {
24新增: Path string `json:"path"`
25新增: Volume uint32 `json:"volume"`
26新增: FileID uint64 `json:"file_id"`
27新增:}
28新增:
29新增:type windowsVMStorageLayout struct {
30新增: Configuration string `json:"configuration"`
31新增: Snapshots string `json:"snapshots"`
32新增: Paging string `json:"paging"`
33新增:}
34新增:
35新增:type windowsHostStorageRequest struct {
36新增: Action string `json:"action"`
37新增: ID string `json:"id,omitempty"`
38新增: SourceVolume uint32 `json:"source_volume,omitempty"`
39新增: SourceFileID uint64 `json:"source_file_id,omitempty"`
40新增: Disk string `json:"disk,omitempty"`
41新增: Directory string `json:"directory,omitempty"`
42新增:}
43新增:
44新增:type windowsHostStorageState struct {
45新增: Disk windowsStorageDisk `json:"disk"`
46新增: Layout *windowsVMStorageLayout `json:"layout,omitempty"`
47新增: Pending string `json:"pending,omitempty"`
48新增: Outcome string `json:"outcome,omitempty"`
49新增:}
50新增:
51新增:func validWindowsStorageID(id string) bool {
52新增: return len(id) == 32 && strings.Trim(id, "0123456789abcdef") == ""
53新增:}
54新增:
55新增:func (r windowsHostStorageRequest) validate() error {
56新增: if r.Action == "status" {
57新增: if r.ID == "" && r.SourceVolume == 0 && r.SourceFileID == 0 && r.Disk == "" && r.Directory == "" {
58新增: return nil
59新增: }
60新增: return errors.New("invalid_request")
61新增: }
62新增: if !validWindowsStorageID(r.ID) || r.SourceVolume == 0 || r.SourceFileID == 0 {
63新增: return errors.New("invalid_request")
64新增: }
65新增: switch r.Action {
66新增: case "begin", "commit", "rollback":
67新增: if r.Disk != "" || r.Directory != "" {
68新增: return errors.New("invalid_request")
69新增: }
70新增: case "attach":
71新增: if r.Disk == "" || r.Directory == "" || len(r.Disk) > 32700 || len(r.Directory) > 32700 || strings.ContainsAny(r.Disk+r.Directory, "\x00\r\n") {
72新增: return errors.New("invalid_request")
73新增: }
74新增: default:
75新增: return errors.New("invalid_request")
76新增: }
77新增: return nil
78新增:}
79新增:
80新增:type windowsHostManagerResponse struct {
81新增: Version int `json:"version"`
82新增: VMID uuid.UUID `json:"vm_id"`
83新增: OK bool `json:"ok"`
84新增: Result json.RawMessage `json:"result,omitempty"`
85新增: Error string `json:"error,omitempty"`
86新增:}
87新增:
88新增:func (r windowsHostManagerRequest) validate() error {
89新增: if r.Version != windowsHostManagerVersion || r.VMID == uuid.Nil {
90新增: return errors.New("invalid_request")
91新增: }
92新增: if r.Operation == "storage" {
93新增: if r.Storage == nil || r.MemoryGiB != 0 || r.CPUs != 0 {
94新增: return errors.New("invalid_request")
95新增: }
96新增: return r.Storage.validate()
97新增: }
98新增: if r.Storage != nil {
99新增: return errors.New("invalid_request")
100新增: }
101新增: switch r.Operation {
102新增: case "inspect", "start", "shutdown":
103新增: if r.MemoryGiB != 0 || r.CPUs != 0 {
104新增: return errors.New("invalid_request")
105新增: }
106新增: case "resources":
107新增: if r.MemoryGiB == 0 && r.CPUs == 0 {
108新增: return nil
109新增: }
110新增: if r.MemoryGiB < 4 || r.MemoryGiB > 1024 || r.CPUs < 2 || r.CPUs > 1024 {
111新增: return errors.New("invalid_request")
112新增: }
113新增: default:
114新增: return errors.New("invalid_operation")
115新增: }
116新增: return nil
117新增:}
新增internal/guestos/windows_host_manager_wire_test.go+22 −0看文件
@@ -0,0 +1,22 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "testing"
5新增:
6新增: "github.com/google/uuid"
7新增:)
8新增:
9新增:func TestWindowsHostManagerRequiresTwoCPUs(t *testing.T) {
10新增: request := windowsHostManagerRequest{Version: 1, VMID: uuid.New(), Operation: "resources", MemoryGiB: 4, CPUs: 1}
11新增: if request.validate() == nil {
12新增: t.Fatal("privileged Windows resource request accepted one CPU below the supported guest minimum")
13新增: }
14新增: request.CPUs = 2
15新增: if err := request.validate(); err != nil {
16新增: t.Fatal("supported Windows CPU minimum rejected", err)
17新增: }
18新增: request.MemoryGiB, request.CPUs = 0, 0
19新增: if err := request.validate(); err != nil {
20新增: t.Fatal("read-only resource request rejected", err)
21新增: }
22新增:}
新增internal/guestos/windows_host_storage_windows.go+579 −0看文件
@@ -0,0 +1,579 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "bytes"
7新增: "context"
8新增: _ "embed"
9新增: "encoding/base64"
10新增: "encoding/json"
11新增: "errors"
12新增: "io"
13新增: "net"
14新增: "os"
15新增: "path/filepath"
16新增: "runtime"
17新增: "strings"
18新增:
19新增: "github.com/google/uuid"
20新增: "golang.org/x/sys/windows"
21新增:
22新增: "github.com/sylvinus/agent-vm/internal/cage"
23新增: "github.com/sylvinus/agent-vm/internal/paths"
24新增:)
25新增:
26新增://go:embed windows_storage.ps1
27新增:var windowsStorageScript string
28新增:
29新增:type windowsHostStorageJournal struct {
30新增: ID string `json:"id"`
31新增: Phase string `json:"phase"`
32新增: Before WindowsHostManagerBinding `json:"before"`
33新增: OldDisk string `json:"old_disk"`
34新增: OldLayout windowsVMStorageLayout `json:"old_layout"`
35新增: After *WindowsHostManagerBinding `json:"after,omitempty"`
36新增: NewLayout *windowsVMStorageLayout `json:"new_layout,omitempty"`
37新增: Directory windowsStorageDisk `json:"directory"`
38新增: Backup string `json:"backup"`
39新增:}
40新增:
41新增:func (server *windowsHostManagerServer) storageJournalPath() string {
42新增: return filepath.Join(filepath.Dir(WindowsHostManagerBindingPath(server.binding.VMID)), "storage.json")
43新增:}
44新增:
45新增:func (server *windowsHostManagerServer) loadStorageJournal() (*windowsHostStorageJournal, error) {
46新增: path := server.storageJournalPath()
47新增: file, err := os.Open(path)
48新增: if errors.Is(err, os.ErrNotExist) {
49新增: return nil, nil
50新增: }
51新增: if err != nil {
52新增: return nil, errors.New("binding_invalid")
53新增: }
54新增: defer file.Close()
55新增: if err = managerProtected(path, server.binding.HostSID); err != nil {
56新增: return nil, err
57新增: }
58新增: var journal windowsHostStorageJournal
59新增: decoder := json.NewDecoder(io.LimitReader(file, windowsHostManagerWireLimit+1))
60新增: decoder.DisallowUnknownFields()
61新增: if decoder.Decode(&journal) != nil || decoder.Decode(new(any)) != io.EOF || !validWindowsStorageID(journal.ID) ||
62新增: journal.Before.VMID != server.binding.VMID || journal.Before.HostSID != server.binding.HostSID ||
63新增: journal.Phase != "pending" && journal.Phase != "commit" && journal.Phase != "rollback" ||
64新增: (journal.After == nil) != (journal.NewLayout == nil) {
65新增: return nil, errors.New("binding_invalid")
66新增: }
67新增: return &journal, nil
68新增:}
69新增:
70新增:func managerProtectStoragePath(path, sid string) error {
71新增: info, err := os.Lstat(path)
72新增: if err != nil || info.Mode()&os.ModeSymlink != 0 {
73新增: return errors.New("binding_invalid")
74新增: }
75新增: inherit := ""
76新增: if info.IsDir() {
77新增: inherit = "OICI"
78新增: }
79新增: sd, err := windows.SecurityDescriptorFromString("O:SYG:SYD:P(A;" + inherit + ";FA;;;SY)(A;" + inherit + ";FA;;;BA)(A;" + inherit + ";FRFX;;;" + sid + ")")
80新增: if err != nil {
81新增: return err
82新增: }
83新增: owner, _, err := sd.Owner()
84新增: if err != nil {
85新增: return err
86新增: }
87新增: acl, _, err := sd.DACL()
88新增: if err != nil {
89新增: return err
90新增: }
91新增: return windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, owner, nil, acl, nil)
92新增:}
93新增:
94新增:func managerWriteStorageJSON(path, sid string, value any) error {
95新增: data, err := json.Marshal(value)
96新增: if err != nil {
97新增: return err
98新增: }
99新增: file, err := os.CreateTemp(filepath.Dir(path), ".storage-*")
100新增: if err != nil {
101新增: return err
102新增: }
103新增: defer os.Remove(file.Name())
104新增: if err = managerProtectStoragePath(file.Name(), sid); err != nil {
105新增: file.Close()
106新增: return err
107新增: }
108新增: _, err = file.Write(data)
109新增: if err == nil {
110新增: err = file.Sync()
111新增: }
112新增: if err = errors.Join(err, file.Close()); err != nil {
113新增: return err
114新增: }
115新增: from, _ := windows.UTF16PtrFromString(file.Name())
116新增: to, err := windows.UTF16PtrFromString(path)
117新增: if err != nil {
118新增: return err
119新增: }
120新增: return windows.MoveFileEx(from, to, windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_WRITE_THROUGH)
121新增:}
122新增:
123新增:func managerStorageCommand(ctx context.Context, id uuid.UUID, action string, input map[string]any, result any) error {
124新增: if input == nil {
125新增: input = make(map[string]any)
126新增: }
127新增: input["vm_id"], input["action"] = id.String(), action
128新增: data, err := json.Marshal(input)
129新增: if err != nil {
130新增: return err
131新增: }
132新增: script := "$inputData = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('" + base64.StdEncoding.EncodeToString(data) + "')) | ConvertFrom-Json\n" + windowsStorageScript
133新增: command, err := systemPowerShellQuery(ctx, script)
134新增: if err != nil {
135新增: return err
136新增: }
137新增: output, err := command.Output()
138新增: if ctx.Err() != nil {
139新增: return ctx.Err()
140新增: }
141新增: if err != nil || len(output) > windowsHostManagerWireLimit || json.Unmarshal(output, result) != nil {
142新增: return errors.New("storage_operation_failed")
143新增: }
144新增: return nil
145新增:}
146新增:
147新增:func (server *windowsHostManagerServer) storageState(journal *windowsHostStorageJournal, outcome string) windowsHostStorageState {
148新增: state := windowsHostStorageState{Disk: windowsStorageDisk{Path: server.binding.DiskPath, Volume: server.binding.DiskVolume, FileID: server.binding.DiskFileID}, Outcome: outcome}
149新增: if journal != nil && journal.Phase == "pending" {
150新增: state.Pending = journal.ID
151新增: }
152新增: return state
153新增:}
154新增:
155新增:func managerRequireStopped(ctx context.Context, binding WindowsHostManagerBinding) error {
156新增: state, err := managerValidateVM(ctx, binding)
157新增: if err != nil {
158新增: return err
159新增: }
160新增: if state.VM.State != "Off" {
161新增: return errors.New("vm_running")
162新增: }
163新增: return nil
164新增:}
165新增:
166新增:func (server *windowsHostManagerServer) storageRequest(ctx context.Context, input windowsHostStorageRequest, journal *windowsHostStorageJournal, conn net.Conn) (any, error) {
167新增: if input.Action == "status" {
168新增: state := server.storageState(journal, "")
169新增: if journal == nil || journal.Phase != "pending" {
170新增: if err := managerRequireStopped(ctx, server.binding); err != nil {
171新增: return nil, err
172新增: }
173新增: var layout windowsVMStorageLayout
174新增: if err := managerStorageCommand(ctx, server.binding.VMID, "inspect", nil, &layout); err != nil {
175新增: return nil, err
176新增: }
177新增: state.Layout = &layout
178新增: }
179新增: return state, nil
180新增: }
181新增: if journal != nil && journal.Phase == "pending" && journal.ID != input.ID {
182新增: return nil, errors.New("storage_pending")
183新增: }
184新增: if journal == nil || journal.Phase != "pending" {
185新增: if journal != nil && journal.ID == input.ID && journal.Phase == input.Action {
186新增: if _, err := managerValidateVM(ctx, server.binding); err != nil {
187新增: return nil, err
188新增: }
189新增: return server.storageState(journal, input.Action), nil
190新增: }
191新增: if server.binding.DiskVolume != input.SourceVolume || server.binding.DiskFileID != input.SourceFileID {
192新增: return nil, errors.New("vm_changed")
193新增: }
194新增: if input.Action == "rollback" {
195新增: if _, err := managerValidateVM(ctx, server.binding); err != nil {
196新增: return nil, err
197新增: }
198新增: return server.storageState(nil, "rollback"), nil
199新增: }
200新增: if input.Action != "begin" {
201新增: return nil, errors.New("invalid_request")
202新增: }
203新增: if err := managerRequireStopped(ctx, server.binding); err != nil {
204新增: return nil, err
205新增: }
206新增: oldDisk, err := managerVMDisk(ctx, server.binding.VMID)
207新增: if err != nil {
208新增: return nil, err
209新增: }
210新增: var layout windowsVMStorageLayout
211新增: if err = managerStorageCommand(ctx, server.binding.VMID, "inspect", nil, &layout); err != nil {
212新增: return nil, err
213新增: }
214新增: backup := filepath.Join(filepath.Dir(server.storageJournalPath()), "storage-backup-"+input.ID)
215新增: journal = &windowsHostStorageJournal{ID: input.ID, Phase: "pending", Before: server.binding, OldDisk: oldDisk, OldLayout: layout, Backup: backup}
216新增: if err = managerWriteStorageJSON(server.storageJournalPath(), server.binding.HostSID, journal); err != nil {
217新增: return nil, err
218新增: }
219新增: }
220新增: if journal.Before.DiskVolume != input.SourceVolume || journal.Before.DiskFileID != input.SourceFileID {
221新增: return nil, errors.New("vm_changed")
222新增: }
223新增: switch input.Action {
224新增: case "begin":
225新增: if err := server.ensureStorageBackup(ctx, journal); err != nil {
226新增: return nil, err
227新增: }
228新增: case "attach":
229新增: if err := server.attachStorage(ctx, journal, input, conn); err != nil {
230新增: return nil, err
231新增: }
232新增: case "commit", "rollback":
233新增: if err := server.finishStorage(ctx, journal, input.Action); err != nil {
234新增: return nil, err
235新增: }
236新增: }
237新增: return server.storageState(journal, input.Action), nil
238新增:}
239新增:
240新增:func (server *windowsHostManagerServer) ensureStorageBackup(ctx context.Context, journal *windowsHostStorageJournal) error {
241新增: complete := filepath.Join(journal.Backup, "cage-export-complete.json")
242新增: if data, err := os.ReadFile(complete); err == nil && bytes.Equal(data, []byte(`{"id":"`+journal.ID+`"}`)) {
243新增: return managerProtected(complete, server.binding.HostSID)
244新增: }
245新增: if journal.After != nil {
246新增: return errors.New("binding_invalid")
247新增: }
248新增: if err := managerRequireStopped(ctx, journal.Before); err != nil {
249新增: return err
250新增: }
251新增: // This directory is created only below the protected fixed-VM registration.
252新增: // Retry a partial metadata export without touching the original VHDX.
253新增: if err := os.RemoveAll(journal.Backup); err != nil {
254新增: return err
255新增: }
256新增: if err := os.Mkdir(journal.Backup, 0700); err != nil {
257新增: return err
258新增: }
259新增: if err := managerProtectStoragePath(journal.Backup, server.binding.HostSID); err != nil {
260新增: return err
261新增: }
262新增: var result struct {
263新增: Exported bool `json:"exported"`
264新增: }
265新增: if err := managerStorageCommand(ctx, server.binding.VMID, "export", map[string]any{"backup": journal.Backup}, &result); err != nil || !result.Exported {
266新增: return errors.Join(err, errors.New("storage_export_failed"))
267新增: }
268新增: return managerWriteStorageJSON(complete, server.binding.HostSID, map[string]string{"id": journal.ID})
269新增:}
270新增:
271新增:// Open the requested object while impersonating the authenticated pipe caller.
272新增:// The resulting handle proves the caller can read, write and manage its ACL.
273新增:// No privileged open is used as a fallback for a denied destination.
274新增:func managerOpenStorageDestination(conn net.Conn, path, hostSID string, directory bool) (windows.Handle, windowsStorageDisk, error) {
275新增: var value windowsStorageDisk
276新增: if !filepath.IsAbs(path) || strings.HasPrefix(path, `\\`) || (!directory && !strings.EqualFold(filepath.Ext(path), ".vhdx")) {
277新增: return 0, value, errors.New("invalid_request")
278新增: }
279新增: file, ok := conn.(interface{ Fd() uintptr })
280新增: if !ok {
281新增: return 0, value, errors.New("unauthorized")
282新增: }
283新增: name, err := windows.UTF16PtrFromString(path)
284新增: if err != nil {
285新增: return 0, value, err
286新增: }
287新增: runtime.LockOSThread()
288新增: defer runtime.UnlockOSThread()
289新增: impersonate := windows.NewLazySystemDLL("advapi32.dll").NewProc("ImpersonateNamedPipeClient")
290新增: okValue, _, callErr := impersonate.Call(file.Fd())
291新增: if okValue == 0 {
292新增: return 0, value, callErr
293新增: }
294新增: flags := uint32(windows.FILE_FLAG_OPEN_REPARSE_POINT)
295新增: if directory {
296新增: flags |= windows.FILE_FLAG_BACKUP_SEMANTICS
297新增: }
298新增: var token windows.Token
299新增: identityErr := windows.OpenThreadToken(windows.CurrentThread(), windows.TOKEN_QUERY, true, &token)
300新增: if identityErr == nil {
301新增: user, err := token.GetTokenUser()
302新增: token.Close()
303新增: if err != nil || user.User.Sid.String() != hostSID {
304新增: identityErr = errors.New("unauthorized")
305新增: }
306新增: }
307新增: var handle windows.Handle
308新增: openErr := identityErr
309新增: if identityErr == nil {
310新增: handle, openErr = windows.CreateFile(name, windows.GENERIC_READ|windows.GENERIC_WRITE|windows.WRITE_DAC|windows.WRITE_OWNER, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, flags, 0)
311新增: }
312新增: if revertErr := windows.RevertToSelf(); revertErr != nil {
313新增: if openErr == nil {
314新增: windows.CloseHandle(handle)
315新增: }
316新增: // Continuing this OS thread with a client's token is unsafe.
317新增: panic("Windows storage impersonation could not be reverted")
318新增: }
319新增: if openErr != nil {
320新增: return 0, value, errors.New("destination_access_denied")
321新增: }
322新增: value, err = managerStorageObject(handle, directory)
323新增: if err != nil {
324新增: windows.CloseHandle(handle)
325新增: return 0, value, err
326新增: }
327新增: return handle, value, nil
328新增:}
329新增:
330新增:// Pin each canonical directory until the privileged operation finishes. A
331新增:// caller may rename a parent between requests, but cannot retarget this request
332新增:// through a replaced directory or an NTFS junction after its access check.
333新增:func managerPinStorageParents(path string) (func(), error) {
334新增: var handles []windows.Handle
335新增: closeAll := func() {
336新增: for _, handle := range handles {
337新增: windows.CloseHandle(handle)
338新增: }
339新增: }
340新增: var parents []string
341新增: for parent := filepath.Dir(path); ; parent = filepath.Dir(parent) {
342新增: parents = append(parents, parent)
343新增: if parent == filepath.Dir(parent) {
344新增: break
345新增: }
346新增: }
347新增: for index := len(parents) - 1; index >= 0; index-- {
348新增: parent := parents[index]
349新增: name, err := windows.UTF16PtrFromString(parent)
350新增: if err != nil {
351新增: closeAll()
352新增: return nil, err
353新增: }
354新增: handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT|windows.FILE_FLAG_BACKUP_SEMANTICS, 0)
355新增: if err != nil {
356新增: closeAll()
357新增: return nil, err
358新增: }
359新增: handles = append(handles, handle)
360新增: actual, err := managerStorageObject(handle, true)
361新增: if err != nil || !strings.EqualFold(filepath.Clean(actual.Path), filepath.Clean(parent)) {
362新增: closeAll()
363新增: return nil, errors.New("vm_changed")
364新增: }
365新增: }
366新增: return closeAll, nil
367新增:}
368新增:
369新增:func managerProtectVMMetadata(handle windows.Handle, sid string, release bool) error {
370新增: owner, access := "SY", "FRFX"
371新增: if release {
372新增: owner, access = sid, "FA"
373新增: }
374新增: sd, err := windows.SecurityDescriptorFromString("O:" + owner + "G:SYD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;" + access + ";;;" + sid + ")")
375新增: if err != nil {
376新增: return err
377新增: }
378新增: ownerSID, _, err := sd.Owner()
379新增: if err != nil {
380新增: return err
381新增: }
382新增: acl, _, err := sd.DACL()
383新增: if err != nil {
384新增: return err
385新增: }
386新增: return windows.SetSecurityInfo(handle, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, ownerSID, nil, acl, nil)
387新增:}
388新增:
389新增:func managerStorageObject(handle windows.Handle, directory bool) (windowsStorageDisk, error) {
390新增: var value windowsStorageDisk
391新增: var info windows.ByHandleFileInformation
392新增: if windows.GetFileInformationByHandle(handle, &info) != nil || info.FileAttributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 || (info.FileAttributes&windows.FILE_ATTRIBUTE_DIRECTORY != 0) != directory {
393新增: return value, errors.New("vm_changed")
394新增: }
395新增: name := make([]uint16, 32768)
396新增: size, err := windows.GetFinalPathNameByHandle(handle, &name[0], uint32(len(name)), 0)
397新增: if err != nil || size == 0 || size >= uint32(len(name)) {
398新增: return value, errors.New("vm_changed")
399新增: }
400新增: path := strings.TrimPrefix(windows.UTF16ToString(name[:size]), `\\?\`)
401新增: if len(filepath.VolumeName(path)) != 2 || strings.HasPrefix(path, `\\`) {
402新增: return value, errors.New("vm_changed")
403新增: }
404新增: return windowsStorageDisk{Path: path, Volume: info.VolumeSerialNumber, FileID: uint64(info.FileIndexHigh)<<32 | uint64(info.FileIndexLow)}, nil
405新增:}
406新增:
407新增:func managerGrantVMDisk(handle windows.Handle, id uuid.UUID) error {
408新增: sid, _, _, err := windows.LookupSID("", `NT VIRTUAL MACHINE\`+id.String())
409新增: if err != nil {
410新增: return err
411新增: }
412新增: sd, err := windows.GetSecurityInfo(handle, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION)
413新增: if err != nil {
414新增: return err
415新增: }
416新增: acl, _, err := sd.DACL()
417新增: if err != nil {
418新增: return err
419新增: }
420新增: var pin runtime.Pinner
421新增: pin.Pin(sid)
422新增: defer pin.Unpin()
423新增: // FILE_ALL_ACCESS from the Windows SDK; x/sys/windows does not export it.
424新增: const fileAllAccess = windows.STANDARD_RIGHTS_REQUIRED | windows.SYNCHRONIZE | 0x1ff
425新增: merged, err := windows.ACLFromEntries([]windows.EXPLICIT_ACCESS{{AccessPermissions: fileAllAccess, AccessMode: windows.GRANT_ACCESS, Trustee: windows.TRUSTEE{TrusteeForm: windows.TRUSTEE_IS_SID, TrusteeType: windows.TRUSTEE_IS_USER, TrusteeValue: windows.TrusteeValueFromSID(sid)}}}, acl)
426新增: if err != nil {
427新增: return err
428新增: }
429新增: return windows.SetSecurityInfo(handle, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION, nil, nil, merged, nil)
430新增:}
431新增:
432新增:func (server *windowsHostManagerServer) attachStorage(ctx context.Context, journal *windowsHostStorageJournal, input windowsHostStorageRequest, conn net.Conn) error {
433新增: if err := server.ensureStorageBackup(ctx, journal); err != nil {
434新增: return err
435新增: }
436新增: diskHandle, disk, err := managerOpenStorageDestination(conn, input.Disk, server.binding.HostSID, false)
437新增: if err != nil {
438新增: return err
439新增: }
440新增: defer windows.CloseHandle(diskHandle)
441新增: diskParents, err := managerPinStorageParents(disk.Path)
442新增: if err != nil {
443新增: return err
444新增: }
445新增: defer diskParents()
446新增: dirHandle, directory, err := managerOpenStorageDestination(conn, input.Directory, server.binding.HostSID, true)
447新增: if err != nil {
448新增: return err
449新增: }
450新增: defer windows.CloseHandle(dirHandle)
451新增: directoryParents, err := managerPinStorageParents(directory.Path)
452新增: if err != nil {
453新增: return err
454新增: }
455新增: defer directoryParents()
456新增: if cage.StoragePathsOverlap(directory.Path, disk.Path) || disk.Volume == journal.Before.DiskVolume && disk.FileID == journal.Before.DiskFileID {
457新增: return errors.New("invalid_request")
458新增: }
459新增: if journal.After == nil {
460新增: entries, err := os.ReadDir(directory.Path)
461新增: if err != nil || len(entries) != 0 {
462新增: return errors.New("destination_not_empty")
463新增: }
464新增: after := journal.Before
465新增: after.DiskPath, after.DiskVolume, after.DiskFileID = disk.Path, disk.Volume, disk.FileID
466新增: layout := windowsVMStorageLayout{Configuration: filepath.Join(directory.Path, "configuration"), Snapshots: filepath.Join(directory.Path, "snapshots"), Paging: filepath.Join(directory.Path, "paging")}
467新增: journal.After, journal.NewLayout, journal.Directory = &after, &layout, directory
468新增: if err = managerWriteStorageJSON(server.storageJournalPath(), server.binding.HostSID, journal); err != nil {
469新增: return err
470新增: }
471新增: } else if journal.After.DiskPath != disk.Path || journal.After.DiskVolume != disk.Volume || journal.After.DiskFileID != disk.FileID || journal.Directory != directory {
472新增: return errors.New("vm_changed")
473新增: }
474新增: if err = managerGrantVMDisk(diskHandle, server.binding.VMID); err != nil {
475新增: return err
476新增: }
477新增: if err = managerProtectVMMetadata(dirHandle, server.binding.HostSID, false); err != nil {
478新增: return err
479新增: }
480新增: if err = server.applyStorage(ctx, journal, *journal.After, *journal.NewLayout); err != nil {
481新增: return err
482新增: }
483新增: return server.saveStorageBinding(*journal.After)
484新增:}
485新增:
486新增:func (server *windowsHostManagerServer) applyStorage(ctx context.Context, journal *windowsHostStorageJournal, binding WindowsHostManagerBinding, layout windowsVMStorageLayout) error {
487新增: name, err := windows.UTF16PtrFromString(binding.DiskPath)
488新增: if err != nil {
489新增: return err
490新增: }
491新增: handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0)
492新增: if err != nil {
493新增: return err
494新增: }
495新增: defer windows.CloseHandle(handle)
496新增: disk, err := managerStorageObject(handle, false)
497新增: if err != nil || !strings.EqualFold(disk.Path, binding.DiskPath) || disk.Volume != binding.DiskVolume || disk.FileID != binding.DiskFileID {
498新增: return errors.New("vm_changed")
499新增: }
500新增: parents, err := managerPinStorageParents(binding.DiskPath)
501新增: if err != nil {
502新增: return err
503新增: }
504新增: defer parents()
505新增: for _, path := range []string{layout.Configuration, layout.Snapshots, layout.Paging} {
506新增: real, err := cage.StoragePhysicalPath(path)
507新增: if err != nil || !filepath.IsAbs(path) || !strings.EqualFold(real, filepath.Clean(path)) {
508新增: return errors.New("vm_changed")
509新增: }
510新增: }
511新增: var result struct {
512新增: Applied bool `json:"applied"`
513新增: }
514新增: if err = managerStorageCommand(ctx, server.binding.VMID, "apply", map[string]any{"old": journal.OldLayout, "next": journal.NewLayout, "target": layout, "old_disk": journal.OldDisk, "source_disk": journal.Before.DiskPath, "new_disk": journal.After.DiskPath, "disk": binding.DiskPath}, &result); err != nil || !result.Applied {
515新增: return errors.Join(err, errors.New("storage_operation_failed"))
516新增: }
517新增: return managerRequireStopped(ctx, binding)
518新增:}
519新增:
520新增:func (server *windowsHostManagerServer) saveStorageBinding(binding WindowsHostManagerBinding) error {
521新增: if err := managerWriteStorageJSON(WindowsHostManagerBindingPath(binding.VMID), binding.HostSID, binding); err != nil {
522新增: return err
523新增: }
524新增: server.binding.DiskPath, server.binding.DiskVolume, server.binding.DiskFileID = binding.DiskPath, binding.DiskVolume, binding.DiskFileID
525新增: return nil
526新增:}
527新增:
528新增:func (server *windowsHostManagerServer) finishStorage(ctx context.Context, journal *windowsHostStorageJournal, action string) error {
529新增: if action == "commit" {
530新增: if journal.After == nil {
531新增: return errors.New("invalid_request")
532新增: }
533新增: if err := managerRequireStopped(ctx, *journal.After); err != nil {
534新增: return err
535新增: }
536新增: var actual windowsVMStorageLayout
537新增: if err := managerStorageCommand(ctx, server.binding.VMID, "inspect", nil, &actual); err != nil || actual != *journal.NewLayout {
538新增: return errors.Join(err, errors.New("vm_changed"))
539新增: }
540新增: if err := server.saveStorageBinding(*journal.After); err != nil {
541新增: return err
542新增: }
543新增: } else {
544新增: if journal.After != nil {
545新增: if err := server.applyStorage(ctx, journal, journal.Before, journal.OldLayout); err != nil {
546新增: return err
547新增: }
548新增: } else if err := managerRequireStopped(ctx, journal.Before); err != nil {
549新增: return err
550新增: }
551新增: if err := server.saveStorageBinding(journal.Before); err != nil {
552新增: return err
553新增: }
554新增: if journal.After != nil {
555新增: // Return the verified metadata directory to its original owner after
556新增: // Hyper-V moves back. Cleanup then runs with that user's permissions.
557新增: real, err := paths.Resolve(journal.Directory.Path)
558新增: if err == nil && strings.EqualFold(real, journal.Directory.Path) {
559新增: name, _ := windows.UTF16PtrFromString(real)
560新增: handle, openErr := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES|windows.WRITE_DAC|windows.WRITE_OWNER, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT|windows.FILE_FLAG_BACKUP_SEMANTICS, 0)
561新增: if openErr != nil {
562新增: return openErr
563新增: }
564新增: defer windows.CloseHandle(handle)
565新增: identity, identityErr := managerStorageObject(handle, true)
566新增: if identityErr != nil || identity != journal.Directory {
567新增: return errors.New("vm_changed")
568新增: }
569新增: if err := managerProtectVMMetadata(handle, server.binding.HostSID, true); err != nil {
570新增: return err
571新增: }
572新增: } else if !errors.Is(err, os.ErrNotExist) {
573新增: return errors.New("vm_changed")
574新增: }
575新增: }
576新增: }
577新增: journal.Phase = action
578新增: return managerWriteStorageJSON(server.storageJournalPath(), server.binding.HostSID, journal)
579新增:}
新增internal/guestos/windows_host_windows.go+96 −0看文件
@@ -0,0 +1,96 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "context"
7新增: "debug/pe"
8新增: "errors"
9新增: "os/exec"
10新增: "path/filepath"
11新增: "runtime"
12新增: "strings"
13新增: "syscall"
14新增: "time"
15新增:
16新增: "golang.org/x/sys/windows"
17新增:)
18新增:
19新增:// probeWindowsHost checks the local platform without requiring VM-wide privileges.
20新增:// It doesn't create a VM or test whether a guest image can be installed.
21新增:func probeWindowsHost(ctx context.Context) (bool, string) {
22新增: version := windows.RtlGetVersion()
23新增: const workstation = 1 // VER_NT_WORKSTATION
24新增: if version.ProductType != workstation || version.MajorVersion < 10 || version.BuildNumber < 22000 {
25新增: return false, "Windows 原生客机需要 Windows 11 桌面版宿主。"
26新增: }
27新增: var processMachine, nativeMachine uint16
28新增: if err := windows.IsWow64Process2(windows.CurrentProcess(), &processMachine, &nativeMachine); err != nil {
29新增: return false, "无法读取 Windows 主机的原生处理器架构。"
30新增: }
31新增: if runtime.GOARCH != "amd64" || nativeMachine != pe.IMAGE_FILE_MACHINE_AMD64 {
32新增: return false, "Windows 原生客机需要 Intel 或 AMD x64 主机及 x64 版 Cage。"
33新增: }
34新增: ctx, cancel := context.WithTimeout(ctx, 12*time.Second)
35新增: defer cancel()
36新增: cmd, err := systemPowerShellQuery(ctx, hyperVHostProbe)
37新增: if err != nil {
38新增: return false, "无法定位系统自带的 Windows PowerShell。"
39新增: }
40新增: output, err := cmd.Output()
41新增: if errors.Is(ctx.Err(), context.DeadlineExceeded) {
42新增: return false, "查询 Hyper-V 超时,请检查本机虚拟机管理服务后重试。"
43新增: }
44新增: if ctx.Err() != nil {
45新增: return false, "已取消 Windows 主机预检。"
46新增: }
47新增: if err != nil {
48新增: var exit *exec.ExitError
49新增: if errors.As(err, &exit) && exit.ExitCode() == 2 {
50新增: if reason := strings.TrimSpace(string(output)); reason != "" {
51新增: return false, reason
52新增: }
53新增: }
54新增: return false, "无法通过系统 PowerShell 查询 Hyper-V,请检查 PowerShell 和 Windows 管理服务。"
55新增: }
56新增: if strings.TrimSpace(string(output)) != "ready" {
57新增: return false, "Hyper-V 预检返回了无法识别的结果。"
58新增: }
59新增: return true, "Hyper-V 平台已就绪;首次安装确认系统授权后,Cage 管理助手仅操作已绑定客机。"
60新增:}
61新增:
62新增:func systemPowerShellQuery(ctx context.Context, script string) (*exec.Cmd, error) {
63新增: systemDir, err := windows.GetSystemDirectory()
64新增: if err != nil {
65新增: return nil, err
66新增: }
67新增: shell := filepath.Join(systemDir, "WindowsPowerShell", "v1.0", "powershell.exe")
68新增: cmd := exec.CommandContext(ctx, shell, "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script)
69新增: cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
70新增: return cmd, nil
71新增:}
72新增:
73新增:const hyperVHostProbe = `
74新增:$ErrorActionPreference = 'Stop'
75新增:[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
76新增:function Unavailable([string]$reason) { Write-Output $reason; exit 2 }
77新增:
78新增:$edition = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name EditionID).EditionID
79新增:if ($edition -like 'Core*') {
80新增: Unavailable 'Windows 家庭版未提供完整的 Hyper-V 角色。此原型支持专业版、企业版和教育版。'
81新增:}
82新增:$service = Get-Service -Name vmms -ErrorAction SilentlyContinue
83新增:if (!$service) {
84新增: Unavailable '未检测到 Hyper-V 虚拟机管理服务(vmms),请检查 Windows 功能中的 Hyper-V 平台。'
85新增:}
86新增:if ($service.Status -ne 'Running') {
87新增: Unavailable 'Hyper-V 虚拟机管理服务(vmms)当前未运行。'
88新增:}
89新增:if ((Get-CimInstance Win32_ComputerSystem).HypervisorPresent -ne $true) {
90新增: Unavailable 'Windows 未检测到正在运行的虚拟机监控程序,请检查固件虚拟化设置和 Hyper-V 启动状态。'
91新增:}
92新增:if (!(Get-Command 'Hyper-V\Get-VMHost' -ErrorAction SilentlyContinue)) {
93新增: Unavailable '缺少 Hyper-V PowerShell 管理模块,请检查 Windows 功能中的 Hyper-V 管理工具。'
94新增:}
95新增:Write-Output 'ready'
96新增:`
新增internal/guestos/windows_lifecycle.go+6 −0看文件
@@ -0,0 +1,6 @@
1新增:package guestos
2新增:
3新增:import _ "embed"
4新增:
5新增://go:embed windows_lifecycle.ps1
6新增:var windowsVMLifecycleScript string
新增internal/guestos/windows_lifecycle.ps1+23 −0看文件
@@ -0,0 +1,23 @@
1新增:$ErrorActionPreference = 'Stop'
2新增:$ProgressPreference = 'SilentlyContinue'
3新增:[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
4新增:$vm = Hyper-V\Get-VM -Id $targetId
5新增:if (!$vm -or $vm.Id -ne $targetId) { throw 'Binding unavailable.' }
6新增:if ($action -eq 'start') {
7新增: if ($vm.Generation -ne 2) { throw 'Guest generation unavailable.' }
8新增: $firmware = Hyper-V\Get-VMFirmware -VM $vm
9新增: $security = Hyper-V\Get-VMSecurity -VM $vm
10新增: if ([string]$firmware.SecureBoot -ne 'On' -or [string]$firmware.SecureBootTemplate -ne 'MicrosoftWindows' -or $security.TpmEnabled -ne $true) { throw 'Guest security unavailable.' }
11新增: # Until Cage's managed exit has a Windows adapter, this guest remains offline.
12新增: if (@(Hyper-V\Get-VMNetworkAdapter -VM $vm).Count -ne 0) { throw 'Controlled exit unavailable.' }
13新增: if ([string]$vm.State -eq 'Off') { Hyper-V\Start-VM -VM $vm | Out-Null }
14新增: elseif ([string]$vm.State -ne 'Running') { throw 'Guest cannot be started from this state.' }
15新增:} elseif ($action -eq 'stop') {
16新增: if ([string]$vm.State -eq 'Running') {
17新增: # Stop-VM without TurnOff/Force requests the guest shutdown integration service.
18新增: Hyper-V\Stop-VM -VM $vm -ErrorAction Stop | Out-Null
19新增: } elseif ([string]$vm.State -ne 'Off') { throw 'Guest cannot be stopped safely from this state.' }
20新增:} else { throw 'Invalid operation.' }
21新增:$vm = Hyper-V\Get-VM -Id $targetId
22新增:if (!$vm -or $vm.Id -ne $targetId) { throw 'Binding changed.' }
23新增:[ordered]@{state=[string]$vm.State} | ConvertTo-Json -Compress
新增internal/guestos/windows_lifecycle_other.go+12 −0看文件
@@ -0,0 +1,12 @@
1新增://go:build !windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "context"
7新增: "errors"
8新增:)
9新增:
10新增:func WindowsVMAction(context.Context, string, string) error {
11新增: return errors.New("Windows 客机生命周期需要 Windows Hyper-V 主机")
12新增:}
新增internal/guestos/windows_lifecycle_test.go+22 −0看文件
@@ -0,0 +1,22 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "os/exec"
5新增: "path/filepath"
6新增: "testing"
7新增:)
8新增:
9新增:func TestWindowsLifecycleExactVMAndSafeShutdown(t *testing.T) {
10新增: shell, err := exec.LookPath("pwsh")
11新增: if err != nil {
12新增: t.Skip("PowerShell not installed")
13新增: }
14新增: query, err := filepath.Abs("windows_lifecycle.ps1")
15新增: if err != nil {
16新增: t.Fatal(err)
17新增: }
18新增: cmd := exec.CommandContext(t.Context(), shell, "-NoLogo", "-NoProfile", "-NonInteractive", "-File", filepath.Join("testdata", "windows_lifecycle.ps1"), "-Query", query)
19新增: if output, err := cmd.CombinedOutput(); err != nil {
20新增: t.Fatalf("lifecycle mock failed: %v\n%s", err, output)
21新增: }
22新增:}
新增internal/guestos/windows_lifecycle_windows.go+64 −0看文件
@@ -0,0 +1,64 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "context"
7新增: "encoding/json"
8新增: "errors"
9新增: "fmt"
10新增:
11新增: "github.com/google/uuid"
12新增:)
13新增:
14新增:// WindowsVMAction controls only the already paired VM. It never creates,
15新增:// discovers, force-powers-off, removes, or changes a guest's network adapters.
16新增:func WindowsVMAction(ctx context.Context, root, action string) error {
17新增: if action != "start" && action != "stop" {
18新增: return errors.New("Windows 客机操作无效")
19新增: }
20新增: binding, err := LoadWindowsProfile(root)
21新增: if err != nil {
22新增: return err
23新增: }
24新增: if binding == nil {
25新增: return errors.New("此配置尚未绑定 Windows 客机")
26新增: }
27新增: operation := action
28新增: if operation == "stop" {
29新增: operation = "shutdown"
30新增: }
31新增: var result WindowsVMResourceState
32新增: if err := windowsHostManagerCall(ctx, binding.VMID, operation, 0, 0, &result); err != nil {
33新增: return err
34新增: }
35新增: if action == "start" && result.State != "Running" || action == "stop" && result.State != "Off" {
36新增: return errors.New("Windows 客机未到达预期状态")
37新增: }
38新增: return nil
39新增:}
40新增:
41新增:func windowsVMActionNative(ctx context.Context, id uuid.UUID, action string) error {
42新增: if id == uuid.Nil || action != "start" && action != "stop" {
43新增: return errors.New("Windows 客机操作无效")
44新增: }
45新增: script := fmt.Sprintf("$targetId = [guid]'%s'\n$action = '%s'\n", id.String(), action) + windowsVMLifecycleScript
46新增: cmd, err := systemPowerShellQuery(ctx, script)
47新增: if err != nil {
48新增: return err
49新增: }
50新增: data, err := cmd.Output()
51新增: if ctx.Err() != nil {
52新增: return ctx.Err()
53新增: }
54新增: if err != nil {
55新增: return errors.New("Windows 客机操作未完成,请检查绑定虚拟机的状态与管理权限")
56新增: }
57新增: var result struct {
58新增: State string `json:"state"`
59新增: }
60新增: if json.Unmarshal(data, &result) != nil || (action == "start" && result.State != "Running") || (action == "stop" && result.State != "Off") {
61新增: return errors.New("Windows 客机未到达预期状态")
62新增: }
63新增: return nil
64新增:}
新增internal/guestos/windows_profile.go+117 −0看文件
@@ -0,0 +1,117 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "bytes"
5新增: "context"
6新增: "encoding/json"
7新增: "errors"
8新增: "io"
9新增: "os"
10新增: "os/exec"
11新增: "path/filepath"
12新增: "regexp"
13新增: "strings"
14新增:
15新增: "github.com/google/uuid"
16新增:)
17新增:
18新增:// WindowsProfile binds one Hyper-V guest to its ordinary GUI user and the
19新增:// current host user's protected pairing. It contains no authentication secret.
20新增:type WindowsProfile struct {
21新增: Version int `json:"version"`
22新增: VMID uuid.UUID `json:"vm_id"`
23新增: GUIUserSID string `json:"gui_user_sid"`
24新增: GUIUser string `json:"gui_user,omitempty"`
25新增: InstanceDirectory string `json:"instance_directory"`
26新增: RelayExecutable string `json:"relay_executable"`
27新增: PairingFile string `json:"pairing_file"`
28新增: NetworkPairingFile string `json:"network_pairing_file,omitempty"`
29新增:}
30新增:
31新增:var windowsGUISID = regexp.MustCompile(`^S-1-5-21-[0-9]+-[0-9]+-[0-9]+-[0-9]+$`)
32新增:
33新增:func WindowsProfilePath(root string) string { return filepath.Join(root, "windows-guest.json") }
34新增:
35新增:func (p WindowsProfile) validate() error {
36新增: if p.Version != 1 || p.VMID == uuid.Nil || !windowsGUISID.MatchString(p.GUIUserSID) ||
37新增: len(p.GUIUser) > 256 || strings.ContainsAny(p.GUIUser, "\x00\r\n") {
38新增: return errors.New("Windows 客机标识或图形用户无效")
39新增: }
40新增: for _, path := range []string{p.InstanceDirectory, p.RelayExecutable, p.PairingFile} {
41新增: if !filepath.IsAbs(path) || strings.ContainsAny(path, "\x00\r\n") {
42新增: return errors.New("Windows 客机配置需要绝对本机路径")
43新增: }
44新增: }
45新增: if p.NetworkPairingFile != "" && (!filepath.IsAbs(p.NetworkPairingFile) || strings.ContainsAny(p.NetworkPairingFile, "\x00\r\n")) {
46新增: return errors.New("Windows 客机网络配对需要绝对本机路径")
47新增: }
48新增: return nil
49新增:}
50新增:
51新增:func LoadWindowsProfile(root string) (*WindowsProfile, error) {
52新增: path := WindowsProfilePath(root)
53新增: info, err := os.Lstat(path)
54新增: if errors.Is(err, os.ErrNotExist) {
55新增: return nil, nil
56新增: }
57新增: if err != nil {
58新增: return nil, err
59新增: }
60新增: if !info.Mode().IsRegular() || info.Size() == 0 || info.Size() > 16<<10 {
61新增: return nil, errors.New("Windows 客机配置文件无效")
62新增: }
63新增: data, err := os.ReadFile(path)
64新增: if err != nil {
65新增: return nil, err
66新增: }
67新增: var binding WindowsProfile
68新增: decoder := json.NewDecoder(bytes.NewReader(data))
69新增: decoder.DisallowUnknownFields()
70新增: if decoder.Decode(&binding) != nil || decoder.Decode(new(any)) != io.EOF {
71新增: return nil, errors.New("Windows 客机配置格式无效")
72新增: }
73新增: if err := binding.validate(); err != nil {
74新增: return nil, err
75新增: }
76新增: return &binding, nil
77新增:}
78新增:
79新增:// BindWindowsProfile publishes an independently verified VM/SID binding.
80新增:// Windows provisioning owns verification and DPAPI pairing; this never discovers
81新增:// a user or VM by scanning the machine and never replaces an existing binding.
82新增:func BindWindowsProfile(root string, binding WindowsProfile) error {
83新增: if err := binding.validate(); err != nil {
84新增: return err
85新增: }
86新增: data, err := json.Marshal(binding)
87新增: if err != nil {
88新增: return err
89新增: }
90新增: if err := publishBinding(root, "windows-guest.json", append(data, '\n')); err != nil {
91新增: return err
92新增: }
93新增: return protectWindowsProfile(WindowsProfilePath(root))
94新增:}
95新增:
96新增:// WindowsRelayCommand carries only the protected profile path and operation.
97新增:// File bytes and UTF-8 path arrays travel in stdin, never a shell or command line.
98新增:func WindowsRelayCommand(ctx context.Context, root, operation string, args ...string) (*exec.Cmd, error) {
99新增: p, err := LoadWindowsProfile(root)
100新增: if err != nil {
101新增: return nil, err
102新增: }
103新增: if p == nil {
104新增: return nil, errors.New("此配置尚未绑定 Windows 客机")
105新增: }
106新增: switch operation {
107新增: case "versions":
108新增: case "stream", "status", "import", "export", "terminal", "browser", "desktop", "attachments", "audio", "resources", "diagnostics", "safety", "project-mount", "network-stream", "network-settings", "cli":
109新增: default:
110新增: return nil, errors.New("Windows 客机剪贴板操作无效")
111新增: }
112新增: if len(args) != 0 && !(operation == "export" && len(args) == 1 && args[0] == "--paths-stdin") {
113新增: return nil, errors.New("Windows 客机文件路径必须通过标准输入传递")
114新增: }
115新增: argv := append([]string{"--relay-profile", WindowsProfilePath(root), operation}, args...)
116新增: return exec.CommandContext(ctx, p.RelayExecutable, argv...), nil
117新增:}
新增internal/guestos/windows_profile_nonwindows.go+6 −0看文件
@@ -0,0 +1,6 @@
1新增://go:build !windows
2新增:
3新增:package guestos
4新增:
5新增:// Non-Windows tests can validate the public binding without interpreting NTFS.
6新增:func protectWindowsProfile(string) error { return nil }
新增internal/guestos/windows_profile_test.go+91 −0看文件
@@ -0,0 +1,91 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "context"
5新增: "encoding/json"
6新增: "os"
7新增: "path/filepath"
8新增: "testing"
9新增:
10新增: "github.com/google/uuid"
11新增:)
12新增:
13新增:func windowsBindingFixture(root string) WindowsProfile {
14新增: return WindowsProfile{Version: 1, VMID: uuid.MustParse("2a6f8208-3906-4e16-8233-2b9d28ecf7be"), GUIUserSID: "S-1-5-21-123-456-789-1001", GUIUser: "Guest", InstanceDirectory: filepath.Join(root, "vm"), RelayExecutable: filepath.Join(root, "agent.exe"), PairingFile: filepath.Join(root, "pairing.dpapi")}
15新增:}
16新增:
17新增:func TestWindowsBindingPreservesIdentityAndHasNoSecretArgument(t *testing.T) {
18新增: root := t.TempDir()
19新增: binding := windowsBindingFixture(root)
20新增: if err := BindWindowsProfile(root, binding); err != nil {
21新增: t.Fatal(err)
22新增: }
23新增: loaded, err := LoadWindowsProfile(root)
24新增: if err != nil || *loaded != binding {
25新增: t.Fatalf("binding changed: %v", err)
26新增: }
27新增: cmd, err := WindowsRelayCommand(context.Background(), root, "export", "--paths-stdin")
28新增: if err != nil {
29新增: t.Fatal(err)
30新增: }
31新增: if len(cmd.Args) != 5 || cmd.Args[1] != "--relay-profile" || cmd.Args[2] != WindowsProfilePath(root) || cmd.Args[3] != "export" || cmd.Args[4] != "--paths-stdin" {
32新增: t.Fatal("relay command did not preserve the profile boundary")
33新增: }
34新增: different := binding
35新增: different.GUIUserSID = "S-1-5-21-123-456-789-1002"
36新增: if err := BindWindowsProfile(root, different); err == nil {
37新增: t.Fatal("another GUI user replaced the binding")
38新增: }
39新增: if _, err := WindowsRelayCommand(context.Background(), root, "export", `["C:\\private"]`); err == nil {
40新增: t.Fatal("paths accepted in argv")
41新增: }
42新增:}
43新增:
44新增:func TestWindowsBindingRejectsUnknownFieldsAndUnsafeIdentity(t *testing.T) {
45新增: for _, kind := range []string{"system", "empty-vm", "relative", "relative-network", "unknown", "trailing"} {
46新增: t.Run(kind, func(t *testing.T) {
47新增: root := t.TempDir()
48新增: binding := windowsBindingFixture(root)
49新增: switch kind {
50新增: case "system":
51新增: binding.GUIUserSID = "S-1-5-18"
52新增: case "empty-vm":
53新增: binding.VMID = uuid.Nil
54新增: case "relative":
55新增: binding.PairingFile = "relative"
56新增: case "relative-network":
57新增: binding.NetworkPairingFile = "packet.dpapi"
58新增: }
59新增: data, _ := json.Marshal(binding)
60新增: if kind == "unknown" {
61新增: data = append(data[:len(data)-1], []byte(`,"secret":"must not be accepted"}`)...)
62新增: }
63新增: if kind == "trailing" {
64新增: data = append(data, []byte(` {}`)...)
65新增: }
66新增: if err := os.WriteFile(WindowsProfilePath(root), data, 0600); err != nil {
67新增: t.Fatal(err)
68新增: }
69新增: if _, err := LoadWindowsProfile(root); err == nil {
70新增: t.Fatal("unsafe binding accepted")
71新增: }
72新增: })
73新增: }
74新增:}
75新增:
76新增:func TestWindowsBindingKeepsPacketPairingOutOfArguments(t *testing.T) {
77新增: root := t.TempDir()
78新增: binding := windowsBindingFixture(root)
79新增: binding.NetworkPairingFile = filepath.Join(root, "packet.dpapi")
80新增: if err := BindWindowsProfile(root, binding); err != nil {
81新增: t.Fatal(err)
82新增: }
83新增: loaded, err := LoadWindowsProfile(root)
84新增: if err != nil || loaded.NetworkPairingFile != binding.NetworkPairingFile {
85新增: t.Fatal("packet pairing binding lost")
86新增: }
87新增: cmd, err := WindowsRelayCommand(context.Background(), root, "network-stream")
88新增: if err != nil || len(cmd.Args) != 4 || cmd.Args[3] != "network-stream" {
89新增: t.Fatal("packet transport bypassed the protected profile")
90新增: }
91新增:}
新增internal/guestos/windows_profile_windows.go+23 −0看文件
@@ -0,0 +1,23 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import "golang.org/x/sys/windows"
6新增:
7新增:// Go's 0600 mode does not establish an NTFS DACL. The relay accepts only a
8新增:// protected binding owned by the current host user, SYSTEM and administrators.
9新增:func protectWindowsProfile(path string) error {
10新增: user, err := windows.GetCurrentProcessToken().GetTokenUser()
11新增: if err != nil {
12新增: return err
13新增: }
14新增: sd, err := windows.SecurityDescriptorFromString("D:P(A;;FA;;;" + user.User.Sid.String() + ")(A;;FA;;;SY)(A;;FA;;;BA)")
15新增: if err != nil {
16新增: return err
17新增: }
18新增: dacl, _, err := sd.DACL()
19新增: if err != nil {
20新增: return err
21新增: }
22新增: return windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, dacl, nil)
23新增:}
新增internal/guestos/windows_resources.go+34 −0看文件
@@ -0,0 +1,34 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "context"
5新增: _ "embed"
6新增:)
7新增:
8新增:// WindowsVMResourceCeiling is the limit enforced by the Hyper-V management service.
9新增:func WindowsVMResourceCeiling(hostMemoryGiB, hostCPUs int) (memoryGiB, cpus int) {
10新增: return min(256, hostMemoryGiB*3/4), min(64, hostCPUs)
11新增:}
12新增:
13新增:type WindowsVMResourceState struct {
14新增: State string `json:"state"`
15新增: CPUs int `json:"cpus"`
16新增: MemoryStartup uint64 `json:"memory_startup_bytes"`
17新增: MemoryMinimum uint64 `json:"memory_minimum_bytes"`
18新增: MemoryMaximum uint64 `json:"memory_maximum_bytes"`
19新增: MemoryAssigned uint64 `json:"memory_assigned_bytes"`
20新增: DynamicMemory bool `json:"dynamic_memory"`
21新增:}
22新增:
23新增:// MatchesAllocation checks the Hyper-V configuration applied on a cold start.
24新增:func (s WindowsVMResourceState) MatchesAllocation(memoryGiB, cpus int) bool {
25新增: return s.DynamicMemory && s.MemoryMinimum == 4<<30 && s.MemoryStartup == 4<<30 &&
26新增: s.MemoryMaximum == uint64(memoryGiB)<<30 && s.CPUs == cpus
27新增:}
28新增:
29新增://go:embed windows_resources.ps1
30新增:var windowsVMResourcesScript string
31新增:
32新增:func WindowsVMResources(ctx context.Context, root string, memoryGiB, cpus int) (WindowsVMResourceState, error) {
33新增: return windowsVMResources(ctx, root, memoryGiB, cpus)
34新增:}
新增internal/guestos/windows_resources.ps1+25 −0看文件
@@ -0,0 +1,25 @@
1新增:$ErrorActionPreference='Stop'
2新增:$ProgressPreference='SilentlyContinue'
3新增:[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false)
4新增:$vm=Hyper-V\Get-VM -Id $targetId
5新增:if(!$vm -or $vm.Id -ne $targetId){throw 'Bound VM unavailable.'}
6新增:$memory=Hyper-V\Get-VMMemory -VM $vm
7新增:$processor=Hyper-V\Get-VMProcessor -VM $vm
8新增:if($memoryGiB -ne 0 -or $cpus -ne 0){
9新增: if($memoryGiB -lt 4 -or $memoryGiB -gt 1024 -or $cpus -lt 1 -or $cpus -gt 1024 -or [string]$vm.State -ne 'Off'){throw 'Stop the guest before applying Windows 11 resources.'}
10新增: $maximum=[int64]$memoryGiB*1GB
11新增: try{
12新增: Hyper-V\Set-VMProcessor -VM $vm -Count $cpus
13新增: Hyper-V\Set-VMMemory -VM $vm -DynamicMemoryEnabled $true -MinimumBytes 4GB -StartupBytes 4GB -MaximumBytes $maximum
14新增: }catch{
15新增: # Restore only the same VM's prior resource settings; keep its disk untouched.
16新增: try{Hyper-V\Set-VMProcessor -VM $vm -Count $processor.Count}catch{}
17新增: try{Hyper-V\Set-VMMemory -VM $vm -DynamicMemoryEnabled $memory.DynamicMemoryEnabled -MinimumBytes $memory.Minimum -StartupBytes $memory.Startup -MaximumBytes $memory.Maximum}catch{}
18新增: throw
19新增: }
20新增: $vm=Hyper-V\Get-VM -Id $targetId
21新增: if(!$vm -or $vm.Id -ne $targetId){throw 'Bound VM changed.'}
22新增: $memory=Hyper-V\Get-VMMemory -VM $vm
23新增: $processor=Hyper-V\Get-VMProcessor -VM $vm
24新增:}
25新增:[ordered]@{state=[string]$vm.State;cpus=[int]$processor.Count;memory_startup_bytes=[uint64]$memory.Startup;memory_minimum_bytes=[uint64]$memory.Minimum;memory_maximum_bytes=[uint64]$memory.Maximum;memory_assigned_bytes=[uint64]$vm.MemoryAssigned;dynamic_memory=[bool]$memory.DynamicMemoryEnabled}|ConvertTo-Json -Compress
新增internal/guestos/windows_resources_other.go+12 −0看文件
@@ -0,0 +1,12 @@
1新增://go:build !windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "context"
7新增: "errors"
8新增:)
9新增:
10新增:func windowsVMResources(context.Context, string, int, int) (WindowsVMResourceState, error) {
11新增: return WindowsVMResourceState{}, errors.New("Windows 客机资源管理需要Windows Hyper-V主机")
12新增:}
新增internal/guestos/windows_resources_test.go+22 −0看文件
@@ -0,0 +1,22 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "os/exec"
5新增: "path/filepath"
6新增: "testing"
7新增:)
8新增:
9新增:func TestWindowsResourceExactVMAndRollback(t *testing.T) {
10新增: shell, err := exec.LookPath("pwsh")
11新增: if err != nil {
12新增: t.Skip("PowerShell not installed")
13新增: }
14新增: query, err := filepath.Abs("windows_resources.ps1")
15新增: if err != nil {
16新增: t.Fatal(err)
17新增: }
18新增: cmd := exec.CommandContext(t.Context(), shell, "-NoLogo", "-NoProfile", "-NonInteractive", "-File", filepath.Join("testdata", "windows_resources.ps1"), "-Query", query)
19新增: if data, err := cmd.CombinedOutput(); err != nil {
20新增: t.Fatalf("Windows resource script failed: %v\n%s", err, data)
21新增: }
22新增:}
新增internal/guestos/windows_resources_windows.go+62 −0看文件
@@ -0,0 +1,62 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "context"
7新增: "encoding/json"
8新增: "errors"
9新增: "fmt"
10新增:
11新增: "github.com/google/uuid"
12新增:)
13新增:
14新增:func windowsVMResources(ctx context.Context, root string, memoryGiB, cpus int) (WindowsVMResourceState, error) {
15新增: if (memoryGiB == 0) != (cpus == 0) || memoryGiB < 0 || memoryGiB > 1024 || cpus < 0 || cpus > 1024 {
16新增: return WindowsVMResourceState{}, errors.New("Windows 客机资源参数无效")
17新增: }
18新增: binding, err := LoadWindowsProfile(root)
19新增: if err != nil {
20新增: return WindowsVMResourceState{}, err
21新增: }
22新增: if binding == nil {
23新增: return WindowsVMResourceState{}, errors.New("此配置尚未绑定Windows客机")
24新增: }
25新增: var result WindowsVMResourceState
26新增: if err := windowsHostManagerCall(ctx, binding.VMID, "resources", memoryGiB, cpus, &result); err != nil {
27新增: return result, err
28新增: }
29新增: if result.CPUs < 1 || result.MemoryStartup < 2<<30 || result.State == "" {
30新增: return result, errors.New("Windows 客机资源状态无效")
31新增: }
32新增: if memoryGiB != 0 && !result.MatchesAllocation(memoryGiB, cpus) {
33新增: return result, errors.New("Windows 客机资源未达到请求值")
34新增: }
35新增: return result, nil
36新增:}
37新增:
38新增:func windowsVMResourcesNative(ctx context.Context, id uuid.UUID, memoryGiB, cpus int) (WindowsVMResourceState, error) {
39新增: if id == uuid.Nil || (memoryGiB == 0) != (cpus == 0) || memoryGiB < 0 || memoryGiB > 1024 || cpus < 0 || cpus > 1024 {
40新增: return WindowsVMResourceState{}, errors.New("Windows 客机资源参数无效")
41新增: }
42新增: script := fmt.Sprintf("$targetId=[guid]'%s'\n$memoryGiB=%d\n$cpus=%d\n", id.String(), memoryGiB, cpus) + windowsVMResourcesScript
43新增: cmd, err := systemPowerShellQuery(ctx, script)
44新增: if err != nil {
45新增: return WindowsVMResourceState{}, err
46新增: }
47新增: data, err := cmd.Output()
48新增: if ctx.Err() != nil {
49新增: return WindowsVMResourceState{}, ctx.Err()
50新增: }
51新增: if err != nil {
52新增: return WindowsVMResourceState{}, errors.New("Windows 客机资源操作未完成,请核对虚拟机状态与管理权限")
53新增: }
54新增: var result WindowsVMResourceState
55新增: if json.Unmarshal(data, &result) != nil || result.CPUs < 1 || result.MemoryStartup < 2<<30 {
56新增: return result, errors.New("Windows 客机资源状态无效")
57新增: }
58新增: if memoryGiB != 0 && !result.MatchesAllocation(memoryGiB, cpus) {
59新增: return result, errors.New("Windows 客机资源未达到请求值")
60新增: }
61新增: return result, nil
62新增:}
新增internal/guestos/windows_storage.go+214 −0看文件
@@ -0,0 +1,214 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "context"
5新增: "encoding/json"
6新增: "errors"
7新增: "fmt"
8新增: "os"
9新增: "path/filepath"
10新增: "strings"
11新增:
12新增: "github.com/google/uuid"
13新增: "github.com/sylvinus/agent-vm/internal/cage"
14新增: "github.com/sylvinus/agent-vm/internal/paths"
15新增:)
16新增:
17新增:type windowsStorageSnapshot struct {
18新增: Profile WindowsProfile `json:"profile"`
19新增: Instance string `json:"instance"`
20新增: Disk windowsStorageDisk `json:"disk"`
21新增:}
22新增:
23新增:type windowsStorageRuntime struct {
24新增: profile string
25新增: call func(context.Context, uuid.UUID, windowsHostStorageRequest) (windowsHostStorageState, error)
26新增:}
27新增:
28新增:func WindowsStorageRuntime(profile string) cage.StorageRuntime {
29新增: return &windowsStorageRuntime{profile: profile, call: windowsHostStorage}
30新增:}
31新增:
32新增:// RecoverWindowsStorage is safe on ordinary startup. The helper is contacted
33新增:// only when a durable Windows storage transaction still needs resolution.
34新增:func RecoverWindowsStorage(ctx context.Context, profile string) error {
35新增: return cage.RecoverStorage(ctx, profile, WindowsStorageRuntime(profile))
36新增:}
37新增:
38新增:func (*windowsStorageRuntime) Name() string { return "windows-hyperv" }
39新增:
40新增:func (runtime *windowsStorageRuntime) Snapshot(ctx context.Context, source string) (cage.StorageRuntimeSnapshot, error) {
41新增: var snapshot cage.StorageRuntimeSnapshot
42新增: binding, err := LoadWindowsProfile(runtime.profile)
43新增: if err != nil {
44新增: return snapshot, err
45新增: }
46新增: if binding == nil {
47新增: return snapshot, errors.New("Windows 客机尚未绑定")
48新增: }
49新增: state, err := runtime.call(ctx, binding.VMID, windowsHostStorageRequest{Action: "status"})
50新增: if err != nil {
51新增: return snapshot, fmt.Errorf("请先更新或恢复 Windows 系统管理助手,再迁移环境存储:%w", err)
52新增: }
53新增: if state.Pending != "" {
54新增: return snapshot, errors.New("这台 Windows 客机仍有待恢复的存储迁移,请打开发起迁移的原工作台")
55新增: }
56新增: instance, err := paths.Resolve(binding.InstanceDirectory)
57新增: if err != nil {
58新增: return snapshot, err
59新增: }
60新增: snapshot.State, err = json.Marshal(windowsStorageSnapshot{Profile: *binding, Instance: instance, Disk: state.Disk})
61新增: if !cage.StorageContains(source, instance) {
62新增: snapshot.Backups = append(snapshot.Backups, instance)
63新增: }
64新增: if !cage.StorageContains(source, state.Disk.Path) && !cage.StorageContains(instance, state.Disk.Path) {
65新增: snapshot.Backups = append(snapshot.Backups, state.Disk.Path)
66新增: }
67新增: if state.Layout != nil {
68新增: // Hyper-V moves and backs up its own configuration and snapshot files.
69新增: // Ordinary host-user copies must not inherit or replace their ACLs.
70新增: for _, directory := range []string{filepath.Join(state.Layout.Configuration, "Virtual Machines"), filepath.Join(state.Layout.Snapshots, "Snapshots")} {
71新增: physical, resolveErr := cage.StoragePhysicalPath(directory)
72新增: if resolveErr != nil {
73新增: return snapshot, resolveErr
74新增: }
75新增: if cage.StorageContains(source, physical) && !cage.StorageContains(physical, state.Disk.Path) {
76新增: snapshot.Excluded = append(snapshot.Excluded, physical)
77新增: }
78新增: }
79新增: }
80新增: return snapshot, err
81新增:}
82新增:
83新增:func windowsMoveSnapshot(move cage.StorageTransition) (windowsStorageSnapshot, error) {
84新增: var snapshot windowsStorageSnapshot
85新增: if json.Unmarshal(move.State, &snapshot) != nil || snapshot.Profile.validate() != nil ||
86新增: !filepath.IsAbs(snapshot.Instance) || !filepath.IsAbs(snapshot.Disk.Path) || snapshot.Disk.Volume == 0 || snapshot.Disk.FileID == 0 {
87新增: return snapshot, errors.New("Windows 存储迁移的恢复信息无效")
88新增: }
89新增: return snapshot, nil
90新增:}
91新增:
92新增:func (runtime *windowsStorageRuntime) action(ctx context.Context, move cage.StorageTransition, action, disk, directory string) error {
93新增: snapshot, err := windowsMoveSnapshot(move)
94新增: if err != nil {
95新增: return err
96新增: }
97新增: state, err := runtime.call(ctx, snapshot.Profile.VMID, windowsHostStorageRequest{Action: action, ID: move.ID,
98新增: SourceVolume: snapshot.Disk.Volume, SourceFileID: snapshot.Disk.FileID, Disk: disk, Directory: directory})
99新增: if err != nil {
100新增: return err
101新增: }
102新增: if action == "begin" || action == "attach" {
103新增: if state.Pending != move.ID {
104新增: return errors.New("Windows 管理助手没有保留当前迁移事务")
105新增: }
106新增: } else if state.Pending != "" || state.Outcome != action {
107新增: return errors.New("Windows 管理助手尚未完成迁移恢复")
108新增: }
109新增: return nil
110新增:}
111新增:
112新增:func (runtime *windowsStorageRuntime) Begin(ctx context.Context, move cage.StorageTransition) error {
113新增: return runtime.action(ctx, move, "begin", "", "")
114新增:}
115新增:
116新增:func windowsMovedPath(value, source, target string) string {
117新增: if !cage.StorageContains(source, value) {
118新增: return value
119新增: }
120新增: rel, err := filepath.Rel(source, value)
121新增: if err != nil {
122新增: return value
123新增: }
124新增: return filepath.Join(target, rel)
125新增:}
126新增:
127新增:func (runtime *windowsStorageRuntime) movedProfile(move cage.StorageTransition, snapshot windowsStorageSnapshot) (WindowsProfile, string) {
128新增: logical := filepath.Join(runtime.profile, "state")
129新增: instance := filepath.Join(logical, "windows-"+strings.ReplaceAll(snapshot.Profile.VMID.String(), "-", ""))
130新增: if cage.StorageContains(move.Source, snapshot.Instance) {
131新增: instance = windowsMovedPath(snapshot.Instance, move.Source, logical)
132新增: }
133新增: next := snapshot.Profile
134新增: next.InstanceDirectory = instance
135新增: remap := func(value string) string {
136新增: value = windowsMovedPath(value, snapshot.Profile.InstanceDirectory, instance)
137新增: value = windowsMovedPath(value, snapshot.Instance, instance)
138新增: return windowsMovedPath(value, move.Source, logical)
139新增: }
140新增: next.RelayExecutable = remap(next.RelayExecutable)
141新增: next.PairingFile = remap(next.PairingFile)
142新增: next.NetworkPairingFile = remap(next.NetworkPairingFile)
143新增: physicalInstance := windowsMovedPath(instance, logical, move.Destination)
144新增: disk := windowsMovedPath(snapshot.Disk.Path, snapshot.Instance, physicalInstance)
145新增: disk = windowsMovedPath(disk, move.Source, move.Destination)
146新增: if disk == snapshot.Disk.Path {
147新增: disk = filepath.Join(physicalInstance, filepath.Base(snapshot.Disk.Path))
148新增: }
149新增: return next, disk
150新增:}
151新增:
152新增:func (runtime *windowsStorageRuntime) Switch(ctx context.Context, move cage.StorageTransition) error {
153新增: snapshot, err := windowsMoveSnapshot(move)
154新增: if err != nil {
155新增: return err
156新增: }
157新增: next, disk := runtime.movedProfile(move, snapshot)
158新增: physicalInstance := windowsMovedPath(next.InstanceDirectory, filepath.Join(runtime.profile, "state"), move.Destination)
159新增: if !cage.StorageContains(move.Source, snapshot.Instance) {
160新增: if err = cage.CopyStorage(ctx, snapshot.Instance, physicalInstance, nil); err != nil {
161新增: return err
162新增: }
163新增: }
164新增: if !cage.StorageContains(move.Source, snapshot.Disk.Path) && !cage.StorageContains(snapshot.Instance, snapshot.Disk.Path) {
165新增: if err = os.MkdirAll(physicalInstance, 0700); err != nil {
166新增: return err
167新增: }
168新增: if err = cage.CopyStorageFile(ctx, snapshot.Disk.Path, disk); err != nil {
169新增: return err
170新增: }
171新增: }
172新增: directory := filepath.Join(move.Destination, "hyperv-"+snapshot.Profile.VMID.String()+"-"+move.ID)
173新增: if err = os.Mkdir(directory, 0700); err != nil {
174新增: return err
175新增: }
176新增: if err = runtime.action(ctx, move, "attach", disk, directory); err != nil {
177新增: return err
178新增: }
179新增: return runtime.writeProfile(snapshot.Profile, next, next)
180新增:}
181新增:
182新增:func (runtime *windowsStorageRuntime) Recover(ctx context.Context, move cage.StorageTransition, committed bool) error {
183新增: snapshot, err := windowsMoveSnapshot(move)
184新增: if err != nil {
185新增: return err
186新增: }
187新增: next, _ := runtime.movedProfile(move, snapshot)
188新增: chosen, action := snapshot.Profile, "rollback"
189新增: if committed {
190新增: chosen, action = next, "commit"
191新增: }
192新增: if err = runtime.action(ctx, move, action, "", ""); err != nil {
193新增: return err
194新增: }
195新增: return runtime.writeProfile(snapshot.Profile, next, chosen)
196新增:}
197新增:
198新增:func (runtime *windowsStorageRuntime) writeProfile(before, after, chosen WindowsProfile) error {
199新增: current, err := LoadWindowsProfile(runtime.profile)
200新增: if err != nil {
201新增: return err
202新增: }
203新增: if current == nil || *current != before && *current != after {
204新增: return errors.New("Windows 客机配对在迁移期间发生变化,请保留迁移记录并核对原配置")
205新增: }
206新增: if *current == chosen {
207新增: return nil
208新增: }
209新增: data, err := json.Marshal(chosen)
210新增: if err != nil {
211新增: return err
212新增: }
213新增: return replaceWindowsStorageProfile(WindowsProfilePath(runtime.profile), append(data, '\n'))
214新增:}
新增internal/guestos/windows_storage.ps1+75 −0看文件
@@ -0,0 +1,75 @@
1新增:$ErrorActionPreference = 'Stop'
2新增:$ProgressPreference = 'SilentlyContinue'
3新增:$id = [guid]$inputData.vm_id
4新增:$vm = Get-VM -Id $id
5新增:if ($vm.State -ne 'Off' -or $vm.Generation -ne 2 -or
6新增: @(Get-VMNetworkAdapter -VM $vm).Count -ne 0 -or
7新增: (Get-VMFirmware -VM $vm).SecureBoot -ne 'On' -or !(Get-VMSecurity -VM $vm).TpmEnabled) {
8新增: throw 'vm_changed'
9新增:}
10新增:$disks = @(Get-VMHardDiskDrive -VM $vm)
11新增:if ($disks.Count -ne 1) { throw 'vm_changed' }
12新增:function Read-Storage {
13新增: $current = Get-VM -Id $id
14新增: [pscustomobject]@{
15新增: configuration = [string]$current.ConfigurationLocation
16新增: snapshots = [string]$current.SnapshotFileLocation
17新增: paging = [string]$current.SmartPagingFilePath
18新增: }
19新增:}
20新增:if ($inputData.action -eq 'inspect') {
21新增: Read-Storage | ConvertTo-Json -Compress
22新增: exit 0
23新增:}
24新增:if ($inputData.action -eq 'export') {
25新增: $namespace = 'root\virtualization\v2'
26新增: $system = Get-WmiObject -Namespace $namespace -Class Msvm_ComputerSystem -Filter ("Name='" + $id.ToString('D') + "'")
27新增: $service = Get-WmiObject -Namespace $namespace -Class Msvm_VirtualSystemManagementService
28新增: $settings = ([wmiclass]'\\.\root\virtualization\v2:Msvm_VirtualSystemExportSettingData').CreateInstance()
29新增: $settings.CopySnapshotConfiguration = 0
30新增: $settings.CopyVmRuntimeInformation = $true
31新增: $settings.CopyVmStorage = $false
32新增: $settings.CreateVmExportSubdirectory = $false
33新增: $result = $service.ExportSystemDefinition($system.__PATH, [string]$inputData.backup, $settings.GetText(1))
34新增: if ($result.ReturnValue -eq 4096) {
35新增: $job = [wmi]$result.Job
36新增: while ($job.JobState -in @(2, 3, 4, 6)) { Start-Sleep -Milliseconds 200; $job.Get() }
37新增: if ($job.JobState -ne 7 -or $job.ErrorCode -ne 0) { throw 'storage_export_failed' }
38新增: } elseif ($result.ReturnValue -ne 0) {
39新增: throw 'storage_export_failed'
40新增: }
41新增: [pscustomobject]@{ exported = $true } | ConvertTo-Json -Compress
42新增: exit 0
43新增:}
44新增:if ($inputData.action -ne 'apply') { throw 'invalid_operation' }
45新增:$old = $inputData.old
46新增:$next = $inputData.next
47新增:$current = Read-Storage
48新增:foreach ($field in @('configuration', 'snapshots', 'paging')) {
49新增: if ($current.$field -ine $old.$field -and $current.$field -ine $next.$field) { throw 'vm_changed' }
50新增:}
51新增:if ($disks[0].Path -ine $inputData.old_disk -and $disks[0].Path -ine $inputData.source_disk -and $disks[0].Path -ine $inputData.new_disk) { throw 'vm_changed' }
52新增:$target = $inputData.target
53新增:$move = @{}
54新增:if ($current.configuration -ine $target.configuration) { $move.VirtualMachinePath = [string]$target.configuration }
55新增:if ($current.snapshots -ine $target.snapshots) { $move.SnapshotFilePath = [string]$target.snapshots }
56新增:if ($current.paging -ine $target.paging) { $move.SmartPagingFilePath = [string]$target.paging }
57新增:if ($move.Count) {
58新增: # Hyper-V owns configuration, vTPM state and snapshot metadata. Its native
59新增: # storage operation preserves the registered VM identity and permissions.
60新增: # The verified VHDX copy is attached separately so its original is retained.
61新增: Move-VMStorage -VM $vm @move -Confirm:$false
62新增:}
63新增:$vm = Get-VM -Id $id
64新增:$disks = @(Get-VMHardDiskDrive -VM $vm)
65新增:if ($vm.State -ne 'Off' -or $disks.Count -ne 1) { throw 'vm_changed' }
66新增:if ($disks[0].Path -ine $inputData.disk) {
67新增: Set-VMHardDiskDrive -VMHardDiskDrive $disks[0] -Path ([string]$inputData.disk)
68新增:}
69新增:$readback = Read-Storage
70新增:foreach ($field in @('configuration', 'snapshots', 'paging')) {
71新增: if ($readback.$field -ine $target.$field) { throw 'storage_readback_failed' }
72新增:}
73新增:$disk = @(Get-VMHardDiskDrive -VM (Get-VM -Id $id))
74新增:if ($disk.Count -ne 1 -or $disk[0].Path -ine $inputData.disk) { throw 'storage_readback_failed' }
75新增:[pscustomobject]@{ applied = $true } | ConvertTo-Json -Compress
新增internal/guestos/windows_storage_nonwindows.go+32 −0看文件
@@ -0,0 +1,32 @@
1新增://go:build !windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "context"
7新增: "errors"
8新增: "os"
9新增: "path/filepath"
10新增:
11新增: "github.com/google/uuid"
12新增:)
13新增:
14新增:func windowsHostStorage(context.Context, uuid.UUID, windowsHostStorageRequest) (windowsHostStorageState, error) {
15新增: return windowsHostStorageState{}, errors.New("Windows 客机存储迁移需要 Windows Hyper-V 主机")
16新增:}
17新增:
18新增:func replaceWindowsStorageProfile(path string, data []byte) error {
19新增: file, err := os.CreateTemp(filepath.Dir(path), ".windows-storage-*")
20新增: if err != nil {
21新增: return err
22新增: }
23新增: defer os.Remove(file.Name())
24新增: _, err = file.Write(data)
25新增: if err == nil {
26新增: err = file.Sync()
27新增: }
28新增: if err = errors.Join(err, file.Close()); err != nil {
29新增: return err
30新增: }
31新增: return os.Rename(file.Name(), path)
32新增:}
新增internal/guestos/windows_storage_windows.go+47 −0看文件
@@ -0,0 +1,47 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "context"
7新增: "errors"
8新增: "os"
9新增: "path/filepath"
10新增:
11新增: "github.com/google/uuid"
12新增: "golang.org/x/sys/windows"
13新增:)
14新增:
15新增:func windowsHostStorage(ctx context.Context, id uuid.UUID, input windowsHostStorageRequest) (windowsHostStorageState, error) {
16新增: var state windowsHostStorageState
17新增: err := windowsHostManagerRequestCall(ctx, windowsHostManagerRequest{Version: windowsHostManagerVersion, VMID: id, Operation: "storage", Storage: &input}, &state)
18新增: return state, err
19新增:}
20新增:
21新增:func replaceWindowsStorageProfile(path string, data []byte) error {
22新增: file, err := os.CreateTemp(filepath.Dir(path), ".windows-storage-*")
23新增: if err != nil {
24新增: return err
25新增: }
26新增: defer os.Remove(file.Name())
27新增: if err = protectWindowsProfile(file.Name()); err != nil {
28新增: file.Close()
29新增: return err
30新增: }
31新增: _, err = file.Write(data)
32新增: if err == nil {
33新增: err = file.Sync()
34新增: }
35新增: if err = errors.Join(err, file.Close()); err != nil {
36新增: return err
37新增: }
38新增: from, err := windows.UTF16PtrFromString(file.Name())
39新增: if err != nil {
40新增: return err
41新增: }
42新增: to, err := windows.UTF16PtrFromString(path)
43新增: if err != nil {
44新增: return err
45新增: }
46新增: return windows.MoveFileEx(from, to, windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_WRITE_THROUGH)
47新增:}
新增internal/hostimage/catalog_other.go+12 −0看文件
@@ -0,0 +1,12 @@
1新增://go:build !windows
2新增:
3新增:package hostimage
4新增:
5新增:import (
6新增: "context"
7新增: "errors"
8新增:)
9新增:
10新增:func expandWindowsCatalog(context.Context, []byte) ([]byte, error) {
11新增: return nil, errors.New("Windows 安装目录需要 Windows 的系统解压组件")
12新增:}
新增internal/hostimage/catalog_windows.go+42 −0看文件
@@ -0,0 +1,42 @@
1新增:package hostimage
2新增:
3新增:import (
4新增: "context"
5新增: "errors"
6新增: "os"
7新增: "os/exec"
8新增: "path/filepath"
9新增: "syscall"
10新增:
11新增: "golang.org/x/sys/windows"
12新增:)
13新增:
14新增:func expandWindowsCatalog(ctx context.Context, data []byte) ([]byte, error) {
15新增: directory, err := os.MkdirTemp("", "cage-system-catalog-")
16新增: if err != nil {
17新增: return nil, err
18新增: }
19新增: defer os.RemoveAll(directory)
20新增: archive := filepath.Join(directory, "products.cab")
21新增: if err = os.WriteFile(archive, data, 0600); err != nil {
22新增: return nil, err
23新增: }
24新增: system, err := windows.GetSystemDirectory()
25新增: if err != nil {
26新增: return nil, err
27新增: }
28新增: command := exec.CommandContext(ctx, filepath.Join(system, "expand.exe"), "-F:products.xml", archive, directory)
29新增: command.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NO_WINDOW}
30新增: if err = command.Run(); err != nil {
31新增: return nil, err
32新增: }
33新增: path := filepath.Join(directory, "products.xml")
34新增: info, err := os.Lstat(path)
35新增: if err != nil {
36新增: return nil, err
37新增: }
38新增: if !info.Mode().IsRegular() || info.Size() > 8<<20 {
39新增: return nil, errors.New("微软安装目录文件无效")
40新增: }
41新增: return os.ReadFile(path)
42新增:}
新增internal/hostimage/download.go+275 −0看文件
@@ -0,0 +1,275 @@
1新增:package hostimage
2新增:
3新增:import (
4新增: "context"
5新增: "crypto/sha256"
6新增: "crypto/sha512"
7新增: "encoding/hex"
8新增: "errors"
9新增: "fmt"
10新增: "hash"
11新增: "io"
12新增: "net/http"
13新增: "os"
14新增: "path/filepath"
15新增: "strings"
16新增: "time"
17新增:)
18新增:
19新增:func digestHash(digest string) (hash.Hash, error) {
20新增: kind, value, ok := strings.Cut(digest, ":")
21新增: decoded, err := hex.DecodeString(value)
22新增: if !ok || err != nil {
23新增: return nil, errors.New("系统镜像摘要无效")
24新增: }
25新增: switch {
26新增: case kind == "sha256" && len(decoded) == sha256.Size:
27新增: return sha256.New(), nil
28新增: case kind == "sha512" && len(decoded) == sha512.Size:
29新增: return sha512.New(), nil
30新增: default:
31新增: return nil, errors.New("系统镜像摘要算法无效")
32新增: }
33新增:}
34新增:
35新增:type progressReader struct {
36新增: ctx context.Context
37新增: reader io.Reader
38新增: out io.Writer
39新增: received int64
40新增: total int64
41新增: activity string
42新增: system string
43新增: last time.Time
44新增:}
45新增:
46新增:func (r *progressReader) Read(p []byte) (int, error) {
47新增: if err := r.ctx.Err(); err != nil {
48新增: return 0, err
49新增: }
50新增: n, err := r.reader.Read(p)
51新增: r.received += int64(n)
52新增: if time.Since(r.last) > 3*time.Second || err == io.EOF || (r.total > 0 && r.received >= r.total) {
53新增: operation := "download"
54新增: if r.activity == "校验系统材料" {
55新增: operation = "verify"
56新增: }
57新增: fmt.Fprintf(r.out, "CAGE_GUEST_BYTES %s %s %d %d\n", r.system, operation, r.received, r.total)
58新增: if r.total > 0 {
59新增: fmt.Fprintf(r.out, "%s %.1f / %.1f MiB(%.0f%%)\n", r.activity, float64(r.received)/(1<<20), float64(r.total)/(1<<20), 100*float64(r.received)/float64(r.total))
60新增: } else {
61新增: fmt.Fprintf(r.out, "%s %.1f MiB\n", r.activity, float64(r.received)/(1<<20))
62新增: }
63新增: r.last = time.Now()
64新增: }
65新增: return n, err
66新增:}
67新增:
68新增:func verify(ctx context.Context, path string, plan Plan, output io.Writer) (string, error) {
69新增: file, err := os.Open(path)
70新增: if err != nil {
71新增: return "", err
72新增: }
73新增: defer file.Close()
74新增: before, err := file.Stat()
75新增: if err != nil {
76新增: return "", err
77新增: }
78新增: if !before.Mode().IsRegular() || (plan.Bytes > 0 && before.Size() != plan.Bytes) ||
79新增: (plan.Modified != 0 && before.ModTime().UnixNano() != plan.Modified) {
80新增: return "", errors.New("本机镜像在选择后发生变化,请重新检查")
81新增: }
82新增: digest := plan.Digest
83新增: if digest == "" {
84新增: digest = "sha256:" + strings.Repeat("0", 64)
85新增: }
86新增: hasher, err := digestHash(digest)
87新增: if err != nil {
88新增: return "", err
89新增: }
90新增: if _, err = io.Copy(hasher, &progressReader{ctx: ctx, reader: file, out: output, total: before.Size(), activity: "校验系统材料", system: plan.Host.System}); err != nil {
91新增: return "", err
92新增: }
93新增: after, err := file.Stat()
94新增: current, pathErr := os.Stat(path)
95新增: if err != nil || pathErr != nil || !os.SameFile(before, current) || after.Size() != before.Size() || after.ModTime() != before.ModTime() {
96新增: return "", errors.New("校验期间系统镜像发生变化,请重新检查")
97新增: }
98新增: actual := strings.SplitN(digest, ":", 2)[0] + ":" + hex.EncodeToString(hasher.Sum(nil))
99新增: if plan.Digest != "" && actual != plan.Digest {
100新增: return "", errors.New("系统镜像摘要不匹配,请重新选择或重新下载")
101新增: }
102新增: if plan.Format == "ipsw" {
103新增: version, build, err := macImageIdentity(path)
104新增: if err != nil || version != plan.Version || build != plan.Build {
105新增: return "", errors.New("恢复镜像内容与已选择的 macOS 版本不一致")
106新增: }
107新增: }
108新增: return actual, nil
109新增:}
110新增:
111新增:// Prepare verifies existing media or resumes the exact pinned download. Only a
112新增:// verified complete archive is published. Interruptions retain the partial file.
113新增:func Prepare(ctx context.Context, cache string, plan Plan, output io.Writer, transport http.RoundTripper) (Plan, error) {
114新增: if err := plan.Validate(); err != nil {
115新增: return Plan{}, err
116新增: }
117新增: if output == nil {
118新增: output = io.Discard
119新增: }
120新增: if plan.Path != "" {
121新增: fmt.Fprintln(output, "正在校验系统镜像…")
122新增: digest, err := verify(ctx, plan.Path, plan, output)
123新增: if err != nil {
124新增: return Plan{}, err
125新增: }
126新增: plan.Digest = digest
127新增: info, err := os.Stat(plan.Path)
128新增: if err != nil {
129新增: return Plan{}, err
130新增: }
131新增: plan.Bytes, plan.Modified = info.Size(), info.ModTime().UnixNano()
132新增: return plan, Save(cache, plan)
133新增: }
134新增: if err := os.MkdirAll(cache, 0700); err != nil {
135新增: return Plan{}, err
136新增: }
137新增: root, err := os.OpenRoot(cache)
138新增: if err != nil {
139新增: return Plan{}, err
140新增: }
141新增: defer root.Close()
142新增: final := filepath.Base(plan.CachedPath(cache))
143新增: if info, err := root.Lstat(final + ".lock"); err == nil && !info.Mode().IsRegular() {
144新增: return Plan{}, errors.New("系统下载锁路径无效")
145新增: }
146新增: lock, err := root.OpenFile(final+".lock", os.O_CREATE|os.O_RDWR, 0600)
147新增: if err != nil {
148新增: return Plan{}, err
149新增: }
150新增: defer lock.Close()
151新增: if err := lockDownload(lock); err != nil {
152新增: return Plan{}, fmt.Errorf("另一项安装正在准备这份系统镜像,请等待它完成后继续:%w", err)
153新增: }
154新增: if info, err := root.Lstat(final); err == nil {
155新增: if !info.Mode().IsRegular() {
156新增: return Plan{}, errors.New("系统材料缓存路径无效")
157新增: }
158新增: plan.Path, plan.Modified = filepath.Join(cache, final), info.ModTime().UnixNano()
159新增: return Prepare(ctx, cache, plan, output, transport)
160新增: } else if !errors.Is(err, os.ErrNotExist) {
161新增: return Plan{}, err
162新增: }
163新增: partial := final + ".partial"
164新增: if info, err := root.Lstat(partial); err == nil && !info.Mode().IsRegular() {
165新增: return Plan{}, errors.New("未完成的系统下载路径无效")
166新增: }
167新增: file, err := root.OpenFile(partial, os.O_CREATE|os.O_RDWR, 0600)
168新增: if err != nil {
169新增: return Plan{}, err
170新增: }
171新增: defer func() { _ = file.Close() }()
172新增: info, err := file.Stat()
173新增: if err != nil {
174新增: return Plan{}, err
175新增: }
176新增: offset := info.Size()
177新增: if plan.Bytes > 0 && offset > plan.Bytes {
178新增: if err = file.Close(); err != nil {
179新增: return Plan{}, err
180新增: }
181新增: if err = root.Rename(partial, partial+".invalid-"+time.Now().UTC().Format("20060102T150405.000000000")); err != nil {
182新增: return Plan{}, err
183新增: }
184新增: file, err = root.OpenFile(partial, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
185新增: if err != nil {
186新增: return Plan{}, err
187新增: }
188新增: offset = 0
189新增: fmt.Fprintln(output, "已保留大小异常的未完成文件,重新下载所选系统材料…")
190新增: }
191新增: if offset != plan.Bytes || plan.Bytes == 0 {
192新增: fmt.Fprintf(output, "正在下载 %s %s 的系统材料,已保留 %.1f MiB…\n", plan.Host.System, plan.Version, float64(offset)/(1<<20))
193新增: err = download(ctx, plan, file, offset, output, transport)
194新增: if err != nil {
195新增: return Plan{}, fmt.Errorf("系统下载中断,已保留进度,可继续安装:%w", err)
196新增: }
197新增: }
198新增: if err = file.Sync(); err != nil {
199新增: return Plan{}, err
200新增: }
201新增: if err = file.Close(); err != nil {
202新增: return Plan{}, err
203新增: }
204新增: if _, err = verify(ctx, filepath.Join(cache, partial), plan, output); err != nil {
205新增: // Preserve the failed download for diagnosis. A new attempt can resume
206新增: // into a new partial file, without reusing corrupt bytes.
207新增: if ctx.Err() == nil {
208新增: _ = root.Rename(partial, partial+".invalid-"+time.Now().UTC().Format("20060102T150405.000000000"))
209新增: }
210新增: return Plan{}, err
211新增: }
212新增: if err = root.Rename(partial, final); err != nil {
213新增: return Plan{}, err
214新增: }
215新增: info, err = root.Stat(final)
216新增: if err != nil {
217新增: return Plan{}, err
218新增: }
219新增: plan.Path, plan.Modified, plan.Bytes = filepath.Join(cache, final), info.ModTime().UnixNano(), info.Size()
220新增: return plan, Save(cache, plan)
221新增:}
222新增:
223新增:func download(ctx context.Context, plan Plan, file *os.File, offset int64, output io.Writer, transport http.RoundTripper) error {
224新增: client := &http.Client{Transport: transport, Timeout: 2 * time.Hour, CheckRedirect: func(request *http.Request, previous []*http.Request) error {
225新增: if len(previous) >= 5 {
226新增: return errors.New("系统下载重定向次数过多")
227新增: }
228新增: return trustedURL(request.URL.String(), plan.Host.System)
229新增: }}
230新增: defer client.CloseIdleConnections()
231新增: request, err := http.NewRequestWithContext(ctx, http.MethodGet, plan.URL, nil)
232新增: if err != nil {
233新增: return err
234新增: }
235新增: request.Header.Set("Accept-Encoding", "identity")
236新增: request.Header.Set("User-Agent", "Mozilla/5.0 (compatible; Cage-SystemInstaller/1.0)")
237新增: if offset > 0 {
238新增: request.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset))
239新增: }
240新增: response, err := client.Do(request)
241新增: if err != nil {
242新增: return err
243新增: }
244新增: defer response.Body.Close()
245新增: switch response.StatusCode {
246新增: case http.StatusOK:
247新增: offset = 0
248新增: if err = file.Truncate(0); err != nil {
249新增: return err
250新增: }
251新增: case http.StatusPartialContent:
252新增: var start, end, total int64
253新增: if _, err = fmt.Sscanf(response.Header.Get("Content-Range"), "bytes %d-%d/%d", &start, &end, &total); err != nil ||
254新增: start != offset || end < start || (plan.Bytes > 0 && total != plan.Bytes) {
255新增: return errors.New("服务器返回的续传范围与原镜像不一致")
256新增: }
257新增: default:
258新增: return fmt.Errorf("系统下载返回 HTTP %d", response.StatusCode)
259新增: }
260新增: if _, err = file.Seek(offset, io.SeekStart); err != nil {
261新增: return err
262新增: }
263新增: limit := int64(64 << 30)
264新增: if plan.Bytes > 0 {
265新增: limit = plan.Bytes
266新增: }
267新增: count, err := io.Copy(file, &progressReader{ctx: ctx, reader: io.LimitReader(response.Body, limit-offset+1), out: output, received: offset, total: plan.Bytes, activity: "下载系统材料", system: plan.Host.System})
268新增: if err != nil {
269新增: return err
270新增: }
271新增: if offset+count > limit || (plan.Bytes > 0 && offset+count != plan.Bytes) {
272新增: return errors.New("下载的系统材料大小不匹配")
273新增: }
274新增: return nil
275新增:}
新增internal/hostimage/identity_unix.go+69 −0看文件
@@ -0,0 +1,69 @@
1新增://go:build !windows
2新增:
3新增:package hostimage
4新增:
5新增:import (
6新增: "context"
7新增: "fmt"
8新增: "os"
9新增: "os/exec"
10新增: "runtime"
11新增: "strconv"
12新增: "strings"
13新增:)
14新增:
15新增:func Host(ctx context.Context) (Identity, error) {
16新增: if runtime.GOOS == "darwin" {
17新增: output, err := exec.CommandContext(ctx, "/usr/bin/sw_vers").Output()
18新增: if err != nil {
19新增: return Identity{}, err
20新增: }
21新增: identity := Identity{System: "macos", Arch: runtime.GOARCH}
22新增: for _, line := range strings.Split(string(output), "\n") {
23新增: key, value, _ := strings.Cut(line, ":")
24新增: switch key {
25新增: case "ProductVersion":
26新增: identity.Version = strings.TrimSpace(value)
27新增: case "BuildVersion":
28新增: identity.Build = strings.TrimSpace(value)
29新增: }
30新增: }
31新增: return identity, nil
32新增: }
33新增: data, err := os.ReadFile("/etc/os-release")
34新增: if err != nil {
35新增: return Identity{}, err
36新增: }
37新增: return linuxIdentity(string(data))
38新增:}
39新增:
40新增:func linuxIdentity(data string) (Identity, error) {
41新增: values := make(map[string]string)
42新增: for _, line := range strings.Split(data, "\n") {
43新增: key, value, ok := strings.Cut(line, "=")
44新增: if !ok {
45新增: continue
46新增: }
47新增: if strings.HasPrefix(value, `"`) {
48新增: unquoted, err := strconv.Unquote(value)
49新增: if err != nil {
50新增: return Identity{}, err
51新增: }
52新增: value = unquoted
53新增: } else {
54新增: value = strings.Trim(value, "'")
55新增: }
56新增: values[key] = value
57新增: }
58新增: version := values["VERSION_ID"]
59新增: if values["ID"] == "debian" {
60新增: version = strings.SplitN(version, ".", 2)[0]
61新增: }
62新增: identity := Identity{System: values["ID"] + "-" + version, Version: version, Arch: runtime.GOARCH}
63新增: switch identity.System {
64新增: case "debian-12", "debian-13", "ubuntu-22.04", "ubuntu-24.04":
65新增: return identity, nil
66新增: default:
67新增: return Identity{}, fmt.Errorf("当前尚未适配 %s 的本机系统创建,仍可选择 Debian 13", values["PRETTY_NAME"])
68新增: }
69新增:}
新增internal/hostimage/identity_unix_test.go+12 −0看文件
@@ -0,0 +1,12 @@
1新增://go:build !windows
2新增:
3新增:package hostimage
4新增:
5新增:import "testing"
6新增:
7新增:func TestUbuntu2204HostIdentity(t *testing.T) {
8新增: identity, err := linuxIdentity("ID=ubuntu\nVERSION_ID=\"22.04\"\nPRETTY_NAME=\"Ubuntu 22.04.5 LTS\"\n")
9新增: if err != nil || identity.System != "ubuntu-22.04" || identity.Version != "22.04" {
10新增: t.Fatalf("identity: %+v %v", identity, err)
11新增: }
12新增:}
新增internal/hostimage/identity_windows.go+71 −0看文件
@@ -0,0 +1,71 @@
1新增:package hostimage
2新增:
3新增:import (
4新增: "context"
5新增: "fmt"
6新增: "runtime"
7新增: "strconv"
8新增: "strings"
9新增:
10新增: "golang.org/x/sys/windows/registry"
11新增:)
12新增:
13新增:func Host(ctx context.Context) (Identity, error) {
14新增: if err := ctx.Err(); err != nil {
15新增: return Identity{}, err
16新增: }
17新增: key, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, registry.QUERY_VALUE)
18新增: if err != nil {
19新增: return Identity{}, err
20新增: }
21新增: defer key.Close()
22新增: version, _, err := key.GetStringValue("DisplayVersion")
23新增: if err != nil {
24新增: return Identity{}, err
25新增: }
26新增: build, _, err := key.GetStringValue("CurrentBuildNumber")
27新增: if err != nil {
28新增: return Identity{}, err
29新增: }
30新增: major, err := strconv.Atoi(build)
31新增: if err != nil || major < 22000 {
32新增: return Identity{}, fmt.Errorf("本机系统创建需要 Windows 11")
33新增: }
34新增: revision, _, err := key.GetIntegerValue("UBR")
35新增: if err != nil {
36新增: return Identity{}, err
37新增: }
38新增: edition, _, err := key.GetStringValue("EditionID")
39新增: if err != nil {
40新增: return Identity{}, err
41新增: }
42新增: languageKey, err := registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Control\MUI\UILanguages`, registry.READ)
43新增: if err != nil {
44新增: return Identity{}, err
45新增: }
46新增: defer languageKey.Close()
47新增: languages, err := languageKey.ReadSubKeyNames(-1)
48新增: if err != nil || len(languages) == 0 {
49新增: return Identity{}, fmt.Errorf("无法读取 Windows 安装语言")
50新增: }
51新增: // InstallLanguage is the base UI language. On multilingual installations,
52新增: // prefer the installed-language key matching the system locale.
53新增: locale, err := registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Control\Nls\Language`, registry.QUERY_VALUE)
54新增: if err == nil {
55新增: defer locale.Close()
56新增: code, _, _ := locale.GetStringValue("InstallLanguage")
57新增: for _, language := range languages {
58新增: candidate, openErr := registry.OpenKey(languageKey, language, registry.QUERY_VALUE)
59新增: if openErr != nil {
60新增: continue
61新增: }
62新增: lcid, _, _ := candidate.GetIntegerValue("LCID")
63新增: candidate.Close()
64新增: if strings.EqualFold(fmt.Sprintf("%04x", lcid), code) {
65新增: languages[0] = language
66新增: break
67新增: }
68新增: }
69新增: }
70新增: return Identity{System: "windows-11", Version: version, Build: fmt.Sprintf("%s.%d", build, revision), Edition: edition, Language: languages[0], Arch: runtime.GOARCH}, nil
71新增:}
新增internal/hostimage/linux_template.go+122 −0看文件
@@ -0,0 +1,122 @@
1新增:package hostimage
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "errors"
6新增: "os"
7新增: "path/filepath"
8新增:)
9新增:
10新增:func linuxTemplateData(plan Plan) ([]byte, error) {
11新增: // These supported cloud images need no distribution-specific template
12新增: // settings. Keep one pinned local image, with no network image fallback.
13新增: value := map[string]any{
14新增: "minimumLimaVersion": "2.0.0",
15新增: "images": []map[string]string{{"location": plan.Path, "arch": map[string]string{"amd64": "x86_64", "arm64": "aarch64"}[plan.Host.Arch], "digest": plan.Digest}},
16新增: }
17新增: return json.Marshal(value)
18新增:}
19新增:
20新增:func WriteLinuxTemplate(state string, plan Plan) error {
21新增: if err := plan.Validate(); err != nil {
22新增: return err
23新增: }
24新增: if !IsLinux(plan.Host.System) || plan.Path == "" || plan.Digest == "" {
25新增: return errors.New("Linux 系统材料尚未准备好")
26新增: }
27新增: data, err := linuxTemplateData(plan)
28新增: if err != nil {
29新增: return err
30新增: }
31新增: dir := filepath.Join(state, "guest-media")
32新增: if err = os.MkdirAll(dir, 0700); err != nil {
33新增: return err
34新增: }
35新增: path := filepath.Join(dir, "host-system.yaml")
36新增: if current, err := os.ReadFile(path); err == nil {
37新增: if string(current) != string(data) {
38新增: return errors.New("Linux 安装已绑定另一份系统材料")
39新增: }
40新增: return Save(dir, plan)
41新增: } else if !errors.Is(err, os.ErrNotExist) {
42新增: return err
43新增: }
44新增: file, err := os.CreateTemp(dir, ".host-system-*.yaml")
45新增: if err != nil {
46新增: return err
47新增: }
48新增: defer os.Remove(file.Name())
49新增: _, err = file.Write(data)
50新增: if err = errors.Join(err, file.Close()); err != nil {
51新增: return err
52新增: }
53新增: if err = os.Rename(file.Name(), path); err != nil {
54新增: return err
55新增: }
56新增: return Save(dir, plan)
57新增:}
58新增:
59新增:// ClearLinuxTemplate releases an unstarted choice while retaining its media.
60新增:func ClearLinuxTemplate(state string, plan Plan) error {
61新增: dir := filepath.Join(state, "guest-media")
62新增: path := filepath.Join(dir, "host-system.yaml")
63新增: data, err := os.ReadFile(path)
64新增: if errors.Is(err, os.ErrNotExist) {
65新增: return nil
66新增: }
67新增: if err != nil {
68新增: return err
69新增: }
70新增: expected, err := linuxTemplateData(plan)
71新增: if err != nil || string(expected) != string(data) {
72新增: return errors.New("本机系统模板归属已变化")
73新增: }
74新增: if err := os.Remove(path); err != nil {
75新增: return err
76新增: }
77新增: if err := os.Remove(filepath.Join(dir, sourceRecord)); !errors.Is(err, os.ErrNotExist) {
78新增: return err
79新增: }
80新增: return nil
81新增:}
82新增:
83新增:func LinuxTemplate(state string) (string, error) {
84新增: path := filepath.Join(state, "guest-media", "host-system.yaml")
85新增: info, err := os.Lstat(path)
86新增: if errors.Is(err, os.ErrNotExist) {
87新增: if _, recordErr := os.Lstat(filepath.Join(state, "guest-media", sourceRecord)); !errors.Is(recordErr, os.ErrNotExist) {
88新增: return "", errors.New("所选 Linux 系统的安装模板缺失,请恢复原环境资料;不会改用其他系统")
89新增: }
90新增: return "template:debian-13", nil
91新增: }
92新增: if err != nil {
93新增: return "", err
94新增: }
95新增: if !info.Mode().IsRegular() || info.Size() > 32<<10 {
96新增: return "", errors.New("本机系统安装模板无效")
97新增: }
98新增: plan, err := Load(filepath.Join(state, "guest-media"))
99新增: if err != nil || !IsLinux(plan.Host.System) {
100新增: return "", errors.New("所选 Linux 系统来源记录无效,请恢复原环境资料")
101新增: }
102新增: expected, err := linuxTemplateData(plan)
103新增: data, readErr := os.ReadFile(path)
104新增: if err != nil || readErr != nil || string(data) != string(expected) {
105新增: return "", errors.New("所选 Linux 系统的模板与来源不一致,请核对原环境资料")
106新增: }
107新增: return path, nil
108新增:}
109新增:
110新增:// LinuxSystem reads the durable image choice, including after installation
111新增:// has finished and its temporary installation record has been removed.
112新增:func LinuxSystem(state string) (string, error) {
113新增: path, err := LinuxTemplate(state)
114新增: if err != nil {
115新增: return "", err
116新增: }
117新增: if path == "template:debian-13" {
118新增: return "debian-13", nil
119新增: }
120新增: plan, err := Load(filepath.Join(state, "guest-media"))
121新增: return plan.Host.System, err
122新增:}
新增internal/hostimage/lock_unix.go+13 −0看文件
@@ -0,0 +1,13 @@
1新增://go:build !windows
2新增:
3新增:package hostimage
4新增:
5新增:import (
6新增: "os"
7新增:
8新增: "golang.org/x/sys/unix"
9新增:)
10新增:
11新增:func lockDownload(file *os.File) error {
12新增: return unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB)
13新增:}
新增internal/hostimage/lock_windows.go+11 −0看文件
@@ -0,0 +1,11 @@
1新增:package hostimage
2新增:
3新增:import (
4新增: "os"
5新增:
6新增: "golang.org/x/sys/windows"
7新增:)
8新增:
9新增:func lockDownload(file *os.File) error {
10新增: return windows.LockFileEx(windows.Handle(file.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, new(windows.Overlapped))
11新增:}
新增internal/hostimage/mac_media.go+86 −0看文件
@@ -0,0 +1,86 @@
1新增:package hostimage
2新增:
3新增:import (
4新增: "archive/zip"
5新增: "encoding/xml"
6新增: "io"
7新增: "os"
8新增: "path/filepath"
9新增: "strings"
10新增:)
11新增:
12新增:func localMacImage(host Identity, directories ...string) (Plan, bool) {
13新增: for _, directory := range directories {
14新增: entries, err := os.ReadDir(directory)
15新增: if err != nil {
16新增: continue
17新增: }
18新增: for _, entry := range entries {
19新增: if !strings.EqualFold(filepath.Ext(entry.Name()), ".ipsw") || entry.Type()&os.ModeSymlink != 0 {
20新增: continue
21新增: }
22新增: path := filepath.Join(directory, entry.Name())
23新增: info, err := entry.Info()
24新增: if err != nil || !info.Mode().IsRegular() || info.Size() <= 0 || info.Size() > 64<<30 {
25新增: continue
26新增: }
27新增: version, build, err := macImageIdentity(path)
28新增: if err != nil || version != host.Version || build != host.Build {
29新增: continue
30新增: }
31新增: return Plan{Host: host, Version: version, Build: build, Format: "ipsw", Bytes: info.Size(), Path: path, Modified: info.ModTime().UnixNano()}, true
32新增: }
33新增: }
34新增: return Plan{}, false
35新增:}
36新增:
37新增:func macImageIdentity(path string) (string, string, error) {
38新增: archive, err := zip.OpenReader(path)
39新增: if err != nil {
40新增: return "", "", err
41新增: }
42新增: defer archive.Close()
43新增: manifest, err := archive.Open("BuildManifest.plist")
44新增: if err != nil {
45新增: return "", "", err
46新增: }
47新增: defer manifest.Close()
48新增: // Apple's universal archives list many hardware variants before the root
49新增: // version fields. The macOS 26.5 manifest alone is over 25 MiB.
50新增: decoder := xml.NewDecoder(io.LimitReader(manifest, 128<<20))
51新增: depth := 0
52新增: var key, version, build string
53新增: for {
54新增: token, err := decoder.Token()
55新增: if err != nil {
56新增: return version, build, err
57新增: }
58新增: switch element := token.(type) {
59新增: case xml.StartElement:
60新增: depth++
61新增: if depth == 3 && element.Name.Local == "key" {
62新增: if err = decoder.DecodeElement(&key, &element); err != nil {
63新增: return "", "", err
64新增: }
65新增: depth--
66新增: } else if depth == 3 && element.Name.Local == "string" {
67新增: var value string
68新增: if err = decoder.DecodeElement(&value, &element); err != nil {
69新增: return "", "", err
70新增: }
71新增: depth--
72新增: switch key {
73新增: case "ProductVersion":
74新增: version = value
75新增: case "ProductBuildVersion":
76新增: build = value
77新增: }
78新增: if version != "" && build != "" {
79新增: return version, build, nil
80新增: }
81新增: }
82新增: case xml.EndElement:
83新增: depth--
84新增: }
85新增: }
86新增:}
新增internal/hostimage/source.go+361 −0看文件
@@ -0,0 +1,361 @@
1新增:// Package hostimage prepares clean installation media matching the host OS.
2新增:// It reads OS identity and installation media without copying personal data.
3新增:package hostimage
4新增:
5新增:import (
6新增: "context"
7新增: "crypto/sha256"
8新增: "encoding/hex"
9新增: "encoding/json"
10新增: "encoding/xml"
11新增: "errors"
12新增: "fmt"
13新增: "io"
14新增: "net/http"
15新增: "net/url"
16新增: "os"
17新增: "path/filepath"
18新增: "regexp"
19新增: "strings"
20新增: "time"
21新增:
22新增: "go.yaml.in/yaml/v3"
23新增: "golang.org/x/mod/semver"
24新增:)
25新增:
26新增:type Identity struct {
27新增: System string `json:"system"`
28新增: Version string `json:"version"`
29新增: Build string `json:"build,omitempty"`
30新增: Edition string `json:"edition,omitempty"`
31新增: Language string `json:"language,omitempty"`
32新增: Arch string `json:"arch"`
33新增:}
34新增:
35新增:func IsLinux(system string) bool {
36新增: return system == "debian-12" || system == "debian-13" || system == "ubuntu-22.04" || system == "ubuntu-24.04"
37新增:}
38新增:
39新增:// Plan is immutable after the user chooses it. Path refers only to source
40新增:// media. Download destinations are derived independently from its digest.
41新增:type Plan struct {
42新增: Host Identity `json:"host"`
43新增: Version string `json:"version"`
44新增: Build string `json:"build,omitempty"`
45新增: Format string `json:"format"`
46新增: URL string `json:"url,omitempty"`
47新增: Digest string `json:"digest,omitempty"`
48新增: Bytes int64 `json:"bytes"`
49新增: Path string `json:"path,omitempty"`
50新增: Modified int64 `json:"modified,omitempty"`
51新增:}
52新增:
53新增:func (p Plan) Key() string {
54新增: if p.URL != "" && p.Digest != "" {
55新增: p.Path, p.Modified = "", 0
56新增: }
57新增: data, _ := json.Marshal(p)
58新增: digest := sha256.Sum256(data)
59新增: return hex.EncodeToString(digest[:])
60新增:}
61新增:
62新增:func (p Plan) Validate() error {
63新增: if p.Host.Arch != "arm64" && p.Host.Arch != "amd64" {
64新增: return errors.New("本机系统架构暂不支持创建客机")
65新增: }
66新增: if p.Version == "" || p.Version != p.Host.Version || p.Bytes < 0 || p.Bytes > 64<<30 {
67新增: return errors.New("系统镜像与本机版本不匹配")
68新增: }
69新增: switch p.Host.System {
70新增: case "macos":
71新增: if p.Format != "ipsw" || p.Build != p.Host.Build || p.Host.Arch != "arm64" {
72新增: return errors.New("macOS 恢复镜像与本机版本不匹配")
73新增: }
74新增: if !semver.IsValid("v"+p.Version) || semver.Compare("v"+p.Version, "v26.4") < 0 {
75新增: return errors.New("自动匹配 macOS 镜像需要本机运行 macOS 26.4 或更新版本,以支持当前工作台使用的 FSKit 只读挂载")
76新增: }
77新增: case "windows-11":
78新增: if p.Format != "esd" || p.Host.Arch != "amd64" || p.Host.Edition == "" || p.Host.Language == "" || p.Build == "" {
79新增: return errors.New("Windows 安装镜像信息不完整")
80新增: }
81新增: case "debian-12", "debian-13", "ubuntu-22.04", "ubuntu-24.04":
82新增: if p.Format != "qcow2" {
83新增: return errors.New("Linux 安装镜像与本机不匹配")
84新增: }
85新增: default:
86新增: return errors.New("当前支持的本机系统为 macOS、Windows 11、Debian 12/13 和 Ubuntu 22.04/24.04")
87新增: }
88新增: if p.Path != "" && (!filepath.IsAbs(p.Path) || filepath.Clean(p.Path) != p.Path || strings.ContainsAny(p.Path, "\r\n\x00")) {
89新增: return errors.New("本机系统镜像路径无效")
90新增: }
91新增: if p.URL != "" {
92新增: if err := trustedURL(p.URL, p.Host.System); err != nil {
93新增: return err
94新增: }
95新增: if _, err := digestHash(p.Digest); err != nil {
96新增: return err
97新增: }
98新增: }
99新增: if p.Path == "" && p.URL == "" {
100新增: return errors.New("缺少系统安装材料")
101新增: }
102新增: return nil
103新增:}
104新增:
105新增:func trustedURL(raw, system string) error {
106新增: u, err := url.Parse(raw)
107新增: if err != nil || u.User != nil || u.Port() != "" || u.Fragment != "" {
108新增: return errors.New("系统材料下载地址无效")
109新增: }
110新增: // Microsoft's HTTPS catalog publishes ESDs on this HTTP-only CDN route.
111新增: // Its pinned SHA-256 is mandatory and verified before any image is applied.
112新增: microsoftESD := system == "windows-11" && u.Scheme == "http" && u.Hostname() == "dl.delivery.mp.microsoft.com"
113新增: if u.Scheme != "https" && !microsoftESD {
114新增: return errors.New("系统材料下载协议无效")
115新增: }
116新增: allowed := map[string][]string{
117新增: "macos": {"updates.cdn-apple.com", "appldnld.apple.com"},
118新增: "windows-11": {"dl.delivery.mp.microsoft.com", "download.microsoft.com", "software.download.prss.microsoft.com"},
119新增: "debian-12": {"cloud.debian.org"}, "debian-13": {"cloud.debian.org"},
120新增: "ubuntu-22.04": {"cloud-images.ubuntu.com"},
121新增: "ubuntu-24.04": {"cloud-images.ubuntu.com"},
122新增: }
123新增: for _, domain := range allowed[system] {
124新增: if u.Hostname() == domain {
125新增: return nil
126新增: }
127新增: }
128新增: return errors.New("系统材料下载地址不属于受支持的系统厂商")
129新增:}
130新增:
131新增:func metadata(ctx context.Context, client *http.Client, address string, out any) error {
132新增: req, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil)
133新增: if err != nil {
134新增: return err
135新增: }
136新增: req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; Cage-SystemInstaller/1.0)")
137新增: response, err := client.Do(req)
138新增: if err != nil {
139新增: return err
140新增: }
141新增: defer response.Body.Close()
142新增: if response.StatusCode != http.StatusOK {
143新增: return fmt.Errorf("系统目录返回 HTTP %d", response.StatusCode)
144新增: }
145新增: data, err := io.ReadAll(io.LimitReader(response.Body, (8<<20)+1))
146新增: if err != nil {
147新增: return err
148新增: }
149新增: if len(data) > 8<<20 {
150新增: return errors.New("系统目录超过大小限制")
151新增: }
152新增: if strings.HasSuffix(address, ".xml") {
153新增: return xml.Unmarshal(data, out)
154新增: }
155新增: return json.Unmarshal(data, out)
156新增:}
157新增:
158新增:// Resolve first reuses previously verified media metadata. Template is the
159新增:// application's bundled, pinned Linux image list, supplied by its owner.
160新增:func Resolve(ctx context.Context, identity Identity, cache, downloads string, template []byte, transport http.RoundTripper) (Plan, error) {
161新增: client := &http.Client{Transport: transport, Timeout: 30 * time.Second}
162新增: if plan, err := Load(cache); err == nil && plan.Host == identity {
163新增: if plan.Path != "" && usableFile(plan.Path, plan.Bytes) {
164新增: info, _ := os.Stat(plan.Path)
165新增: if info.ModTime().UnixNano() == plan.Modified {
166新增: return plan, nil
167新增: }
168新增: }
169新增: if path := plan.CachedPath(cache); usableFile(path, plan.Bytes) {
170新增: plan.Path = path
171新增: info, _ := os.Stat(path)
172新增: plan.Modified = info.ModTime().UnixNano()
173新增: return plan, plan.Validate()
174新增: }
175新增: }
176新增: var plan Plan
177新增: var err error
178新增: switch identity.System {
179新增: case "macos":
180新增: if plan, ok := localMacImage(identity, cache, downloads); ok {
181新增: return plan, plan.Validate()
182新增: }
183新增: plan, err = macCatalog(ctx, client, identity)
184新增: case "windows-11":
185新增: plan, err = windowsCatalog(ctx, client, identity)
186新增: default:
187新增: plan, err = linuxCatalog(identity, template)
188新增: }
189新增: if err != nil {
190新增: return Plan{}, err
191新增: }
192新增: for _, candidate := range []string{plan.CachedPath(cache), filepath.Join(downloads, filepath.Base(plan.URL))} {
193新增: if usableFile(candidate, plan.Bytes) {
194新增: info, _ := os.Stat(candidate)
195新增: plan.Path, plan.Modified = candidate, info.ModTime().UnixNano()
196新增: if plan.Bytes == 0 {
197新增: plan.Bytes = info.Size()
198新增: }
199新增: break
200新增: }
201新增: }
202新增: return plan, plan.Validate()
203新增:}
204新增:
205新增:func usableFile(path string, size int64) bool {
206新增: info, err := os.Lstat(path)
207新增: return err == nil && info.Mode().IsRegular() && info.Size() > 0 && (size == 0 || info.Size() == size)
208新增:}
209新增:
210新增:func macCatalog(ctx context.Context, client *http.Client, host Identity) (Plan, error) {
211新增: // IPSW.me indexes historical Apple URLs. The archive is fetched only from
212新增: // Apple and independently verified by Apple's installer before restoration.
213新增: var catalog struct {
214新增: Firmware []struct {
215新增: Version string `json:"version"`
216新增: Build string `json:"buildid"`
217新增: URL string `json:"url"`
218新增: Bytes int64 `json:"filesize"`
219新增: SHA256 string `json:"sha256sum"`
220新增: } `json:"firmwares"`
221新增: }
222新增: if err := metadata(ctx, client, "https://api.ipsw.me/v4/device/VirtualMac2,1?type=ipsw", &catalog); err != nil {
223新增: return Plan{}, fmt.Errorf("查找与本机一致的 Apple 恢复镜像失败,可选择已有 IPSW:%w", err)
224新增: }
225新增: for _, media := range catalog.Firmware {
226新增: if media.Version == host.Version && media.Build == host.Build {
227新增: return Plan{Host: host, Version: media.Version, Build: media.Build, Format: "ipsw", URL: media.URL, Digest: "sha256:" + media.SHA256, Bytes: media.Bytes}, nil
228新增: }
229新增: }
230新增: return Plan{}, fmt.Errorf("未找到 macOS %s(%s)的恢复镜像,请选择已有的对应 IPSW", host.Version, host.Build)
231新增:}
232新增:
233新增:const windowsCatalogURL = "https://download.microsoft.com/download/eb1cc454-1c9a-4c94-adf8-b30c7f3d03d1/products.xml"
234新增:
235新增:type windowsMediaCatalog struct {
236新增: Files []struct {
237新增: Name string `xml:"FileName"`
238新增: Language string `xml:"LanguageCode"`
239新增: Edition string `xml:"Edition"`
240新增: Arch string `xml:"Architecture"`
241新增: Bytes int64 `xml:"Size"`
242新增: SHA256 string `xml:"Sha256"`
243新增: URL string `xml:"FilePath"`
244新增: } `xml:"Files>File"`
245新增:}
246新增:
247新增:func windowsCatalog(ctx context.Context, client *http.Client, host Identity) (Plan, error) {
248新增: current, currentErr := currentWindowsCatalog(ctx, client, host)
249新增: if currentErr == nil {
250新增: if plan, ok := selectWindowsMedia(current, host); ok {
251新增: return plan, nil
252新增: }
253新增: }
254新增: // Microsoft's current catalog can omit an older feature release. Keep the
255新增: // published 25H2 catalog as a fallback, without changing the selected release.
256新增: var catalog windowsMediaCatalog
257新增: if err := metadata(ctx, client, windowsCatalogURL, &catalog); err != nil {
258新增: return Plan{}, fmt.Errorf("读取微软安装目录失败,可选择已有 ISO:%w", err)
259新增: }
260新增: if plan, ok := selectWindowsMedia(catalog, host); ok {
261新增: return plan, nil
262新增: }
263新增: if currentErr != nil {
264新增: return Plan{}, fmt.Errorf("无法读取匹配本机版本的微软目录,请检查所选代理后重试:%w", currentErr)
265新增: }
266新增: return Plan{}, fmt.Errorf("微软当前目录没有 Windows 11 %s %s %s 的对应介质,请选择已有 ISO", host.Version, host.Edition, host.Language)
267新增:}
268新增:
269新增:func selectWindowsMedia(catalog windowsMediaCatalog, host Identity) (Plan, bool) {
270新增: major := strings.SplitN(host.Build, ".", 2)[0]
271新增: for _, file := range catalog.Files {
272新增: if file.Arch != "x64" || file.Edition != host.Edition || !strings.EqualFold(file.Language, host.Language) ||
273新增: major == "" || !strings.HasPrefix(file.Name, major+".") {
274新增: continue
275新增: }
276新增: build := regexp.MustCompile(`^\d+\.\d+`).FindString(file.Name)
277新增: return Plan{Host: host, Version: host.Version, Build: build, Format: "esd", Bytes: file.Bytes,
278新增: Digest: "sha256:" + strings.ToLower(file.SHA256), URL: file.URL}, true
279新增: }
280新增: return Plan{}, false
281新增:}
282新增:
283新增:func linuxCatalog(host Identity, template []byte) (Plan, error) {
284新增: var config struct {
285新增: Images []struct {
286新增: Location string `yaml:"location"`
287新增: Arch string `yaml:"arch"`
288新增: Digest string `yaml:"digest"`
289新增: Bytes int64 `yaml:"bytes"`
290新增: } `yaml:"images"`
291新增: }
292新增: if err := yaml.Unmarshal(template, &config); err != nil {
293新增: return Plan{}, err
294新增: }
295新增: arch := map[string]string{"amd64": "x86_64", "arm64": "aarch64"}[host.Arch]
296新增: for _, image := range config.Images {
297新增: if arch != "" && image.Arch == arch && image.Digest != "" {
298新增: return Plan{Host: host, Version: host.Version, Format: "qcow2", URL: image.Location, Digest: image.Digest, Bytes: image.Bytes}, nil
299新增: }
300新增: }
301新增: return Plan{}, errors.New("此安装包缺少与本机发行版一致的已校验 Linux 镜像")
302新增:}
303新增:
304新增:func (p Plan) CachedPath(cache string) string {
305新增: key := strings.ReplaceAll(p.Digest, ":", "-")
306新增: if key == "" {
307新增: key = p.Key()
308新增: }
309新增: return filepath.Join(cache, key+"."+p.Format)
310新增:}
311新增:
312新增:func (p Plan) RemainingBytes(cache string) int64 {
313新增: if p.Path != "" {
314新增: return 0
315新增: }
316新增: if usableFile(p.CachedPath(cache), p.Bytes) {
317新增: return 0
318新增: }
319新增: info, err := os.Lstat(p.CachedPath(cache) + ".partial")
320新增: if err == nil && info.Mode().IsRegular() && info.Size() <= p.Bytes {
321新增: return p.Bytes - info.Size()
322新增: }
323新增: return p.Bytes
324新增:}
325新增:
326新增:const sourceRecord = "host-system-source.json"
327新增:
328新增:func Save(cache string, plan Plan) error {
329新增: if err := plan.Validate(); err != nil {
330新增: return err
331新增: }
332新增: if err := os.MkdirAll(cache, 0700); err != nil {
333新增: return err
334新增: }
335新增: file, err := os.CreateTemp(cache, ".host-system-source-*")
336新增: if err != nil {
337新增: return err
338新增: }
339新增: defer os.Remove(file.Name())
340新增: err = json.NewEncoder(file).Encode(plan)
341新增: closeErr := file.Close()
342新增: if err = errors.Join(err, closeErr); err != nil {
343新增: return err
344新增: }
345新增: return os.Rename(file.Name(), filepath.Join(cache, sourceRecord))
346新增:}
347新增:
348新增:func Load(cache string) (Plan, error) {
349新增: var plan Plan
350新增: file, err := os.Open(filepath.Join(cache, sourceRecord))
351新增: if err != nil {
352新增: return plan, err
353新增: }
354新增: defer file.Close()
355新增: decoder := json.NewDecoder(io.LimitReader(file, 32<<10))
356新增: decoder.DisallowUnknownFields()
357新增: if err = decoder.Decode(&plan); err != nil {
358新增: return plan, err
359新增: }
360新增: return plan, plan.Validate()
361新增:}
新增internal/hostimage/source_test.go+298 −0看文件
@@ -0,0 +1,298 @@
1新增:package hostimage
2新增:
3新增:import (
4新增: "archive/zip"
5新增: "bytes"
6新增: "context"
7新增: "crypto/sha256"
8新增: "encoding/hex"
9新增: "encoding/json"
10新增: "encoding/xml"
11新增: "fmt"
12新增: "io"
13新增: "net"
14新增: "net/http"
15新增: "net/http/httptest"
16新增: "os"
17新增: "path/filepath"
18新增: "runtime"
19新增: "strings"
20新增: "testing"
21新增:
22新增: "github.com/sylvinus/agent-vm/internal/cage"
23新增:)
24新增:
25新增:func TestMacSourceReadsIdentityWithoutUserFiles(t *testing.T) {
26新增: dir := t.TempDir()
27新增: path := filepath.Join(dir, "system.ipsw")
28新增: file, err := os.Create(path)
29新增: if err != nil {
30新增: t.Fatal(err)
31新增: }
32新增: archive := zip.NewWriter(file)
33新增: manifest, _ := archive.Create("BuildManifest.plist")
34新增: fmt.Fprint(manifest, `<plist><dict><key>BuildIdentities</key><array><dict><key>ProductVersion</key><string>wrong</string></dict>`)
35新增: // Universal IPSWs place their root identity after a large hardware list.
36新增: fmt.Fprint(manifest, strings.Repeat(" ", 17<<20))
37新增: fmt.Fprint(manifest, `</array><key>ProductVersion</key><string>26.5</string><key>ProductBuildVersion</key><string>25F71</string></dict></plist>`)
38新增: if err = archive.Close(); err != nil {
39新增: t.Fatal(err)
40新增: }
41新增: file.Close()
42新增: host := Identity{System: "macos", Version: "26.5", Build: "25F71", Arch: "arm64"}
43新增: plan, ok := localMacImage(host, dir)
44新增: if !ok || plan.Path != path {
45新增: t.Fatalf("source not found: %+v", plan)
46新增: }
47新增: prepared, err := Prepare(t.Context(), filepath.Join(dir, "cache"), plan, io.Discard, nil)
48新增: if err != nil || !strings.HasPrefix(prepared.Digest, "sha256:") {
49新增: t.Fatalf("prepare: %+v %v", prepared, err)
50新增: }
51新增: host.Build = "25F84"
52新增: if _, ok := localMacImage(host, dir); ok {
53新增: t.Fatal("accepted different macOS build")
54新增: }
55新增:}
56新增:
57新增:func TestSourceRejectsUntrustedURLsAndUnsupportedSystems(t *testing.T) {
58新增: base := Plan{Host: Identity{System: "macos", Version: "26.5", Build: "25F71", Arch: "arm64"}, Version: "26.5", Build: "25F71", Format: "ipsw", Digest: "sha256:" + strings.Repeat("a", 64), URL: "https://updates.cdn-apple.com/system.ipsw"}
59新增: if err := base.Validate(); err != nil {
60新增: t.Fatal(err)
61新增: }
62新增: for _, url := range []string{"http://updates.cdn-apple.com/a", "https://updates.cdn-apple.com.evil.test/a", "https://[email protected]/a", "https://updates.cdn-apple.com:443/a"} {
63新增: plan := base
64新增: plan.URL = url
65新增: if err := plan.Validate(); err == nil {
66新增: t.Errorf("accepted %q", url)
67新增: }
68新增: }
69新增: base.Host.System = "arch-linux"
70新增: if err := base.Validate(); err == nil {
71新增: t.Fatal("accepted unsupported source")
72新增: }
73新增:}
74新增:
75新增:func TestMacCloneRequiresGuestFileSystemSupport(t *testing.T) {
76新增: for _, version := range []string{"14.7.6", "15.4", "26.3", "26.4", "26.5"} {
77新增: plan := Plan{Host: Identity{System: "macos", Version: version, Build: "fixture", Arch: "arm64"}, Version: version,
78新增: Build: "fixture", Format: "ipsw", Path: filepath.Join(t.TempDir(), "system.ipsw")}
79新增: err := plan.Validate()
80新增: allowed := version == "26.4" || version == "26.5"
81新增: if (err == nil) != allowed {
82新增: t.Fatalf("version %s: %v", version, err)
83新增: }
84新增: }
85新增:}
86新增:
87新增:func TestSourceKeyAndSpaceAllowCompletedConcurrentDownload(t *testing.T) {
88新增: cache := t.TempDir()
89新增: plan := Plan{Host: Identity{System: "windows-11", Version: "25H2", Arch: "amd64", Edition: "Professional", Language: "en-US"}, Version: "25H2", Build: "26200.1", Format: "esd", URL: "http://dl.delivery.mp.microsoft.com/example.esd", Digest: "sha256:" + strings.Repeat("a", 64), Bytes: 10}
90新增: if err := plan.Validate(); err != nil {
91新增: t.Fatal(err)
92新增: }
93新增: if err := os.WriteFile(plan.CachedPath(cache)+".partial", []byte("123456"), 0600); err != nil {
94新增: t.Fatal(err)
95新增: }
96新增: if remaining := plan.RemainingBytes(cache); remaining != 4 {
97新增: t.Fatalf("remaining=%d", remaining)
98新增: }
99新增: ready := plan
100新增: ready.Path = plan.CachedPath(cache)
101新增: ready.Modified = 123
102新增: if ready.Key() != plan.Key() {
103新增: t.Fatal("a completed cache invalidated the selected image")
104新增: }
105新增: if remaining := ready.RemainingBytes(cache); remaining != 0 {
106新增: t.Fatalf("ready remaining=%d", remaining)
107新增: }
108新增: plan.Digest = ""
109新增: if err := plan.Validate(); err == nil {
110新增: t.Fatal("accepted HTTP media without the HTTPS catalog digest")
111新增: }
112新增:}
113新增:
114新增:func TestWindowsCatalogKeepsFeatureReleaseAndEdition(t *testing.T) {
115新增: var catalog windowsMediaCatalog
116新增: data := `<PublishedMedia><Files><File><FileName>26300.9457.26h2_release.esd</FileName><LanguageCode>zh-cn</LanguageCode><Edition>Professional</Edition><Architecture>x64</Architecture><Size>100</Size><Sha256>` + strings.Repeat("a", 64) + `</Sha256><FilePath>http://dl.delivery.mp.microsoft.com/windows.esd</FilePath></File></Files></PublishedMedia>`
117新增: if err := xml.Unmarshal([]byte(data), &catalog); err != nil {
118新增: t.Fatal(err)
119新增: }
120新增: host := Identity{System: "windows-11", Version: "26H2", Build: "26300.9711", Edition: "Professional", Language: "zh-CN", Arch: "amd64"}
121新增: plan, ok := selectWindowsMedia(catalog, host)
122新增: if !ok || plan.Build != "26300.9457" || plan.Version != "26H2" {
123新增: t.Fatalf("catalog match: %+v %v", plan, ok)
124新增: }
125新增: if err := plan.Validate(); err != nil {
126新增: t.Fatal(err)
127新增: }
128新增: host.Build = "26200.9711"
129新增: host.Version = "25H2"
130新增: if _, ok := selectWindowsMedia(catalog, host); ok {
131新增: t.Fatal("silently changed the Windows feature release")
132新增: }
133新增: host.Build = "26300.9711"
134新增: host.Edition = "Enterprise"
135新增: if _, ok := selectWindowsMedia(catalog, host); ok {
136新增: t.Fatal("silently changed the Windows edition")
137新增: }
138新增:}
139新增:
140新增:func TestDownloadResumesAndRejectsWrongRange(t *testing.T) {
141新增: for _, wrong := range []bool{false, true} {
142新增: t.Run(fmt.Sprint(wrong), func(t *testing.T) {
143新增: server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
144新增: if r.Header.Get("Range") != "bytes=3-" {
145新增: t.Error("did not request resume")
146新增: }
147新增: start := 3
148新增: if wrong {
149新增: start = 2
150新增: }
151新增: w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-5/6", start))
152新增: w.WriteHeader(http.StatusPartialContent)
153新增: fmt.Fprint(w, "def")
154新增: }))
155新增: defer server.Close()
156新增: file, err := os.CreateTemp(t.TempDir(), "partial")
157新增: if err != nil {
158新增: t.Fatal(err)
159新增: }
160新增: defer file.Close()
161新增: file.WriteString("abc")
162新增: var progress bytes.Buffer
163新增: err = download(t.Context(), Plan{Host: Identity{System: "windows-11"}, URL: server.URL, Bytes: 6}, file, 3, &progress, nil)
164新增: if wrong {
165新增: if err == nil {
166新增: t.Fatal("accepted wrong range")
167新增: }
168新增: return
169新增: }
170新增: if err != nil {
171新增: t.Fatal(err)
172新增: }
173新增: data, _ := os.ReadFile(file.Name())
174新增: if string(data) != "abcdef" {
175新增: t.Fatalf("got %q", data)
176新增: }
177新增: if !strings.Contains(progress.String(), "CAGE_GUEST_BYTES windows-11 download 6 6") {
178新增: t.Fatalf("missing actual resumed byte progress: %s", progress.String())
179新增: }
180新增: })
181新增: }
182新增:}
183新增:
184新增:func TestPrepareRejectsModifiedSourceAndPreservesIt(t *testing.T) {
185新增: dir := t.TempDir()
186新增: path := filepath.Join(dir, "system.esd")
187新增: os.WriteFile(path, []byte("original"), 0600)
188新增: info, _ := os.Stat(path)
189新增: digest := sha256.Sum256([]byte("original"))
190新增: plan := Plan{Host: Identity{System: "windows-11", Version: "25H2", Build: "26200.9", Edition: "Professional", Language: "en-US", Arch: "amd64"}, Version: "25H2", Build: "26200.8", Format: "esd", Path: path, Bytes: 8, Modified: info.ModTime().UnixNano(), Digest: "sha256:" + hex.EncodeToString(digest[:])}
191新增: os.WriteFile(path, []byte("tampered"), 0600)
192新增: if _, err := Prepare(t.Context(), filepath.Join(dir, "cache"), plan, io.Discard, nil); err == nil {
193新增: t.Fatal("accepted changed source")
194新增: }
195新增: data, _ := os.ReadFile(path)
196新增: if string(data) != "tampered" {
197新增: t.Fatal("changed user's source")
198新增: }
199新增:}
200新增:
201新增:func TestPrepareRecoversOversizedPartialWithoutDiscardingIt(t *testing.T) {
202新增: cache := t.TempDir()
203新增: content := []byte("valid image")
204新增: digest := sha256.Sum256(content)
205新增: plan := Plan{
206新增: Host: Identity{System: "windows-11", Version: "25H2", Build: "26200.9", Edition: "Professional", Language: "en-US", Arch: "amd64"},
207新增: Version: "25H2", Build: "26200.8", Format: "esd", Bytes: int64(len(content)),
208新增: URL: "http://dl.delivery.mp.microsoft.com/fixture.esd", Digest: "sha256:" + hex.EncodeToString(digest[:]),
209新增: }
210新增: partial := plan.CachedPath(cache) + ".partial"
211新增: bad := []byte("oversized incomplete response")
212新增: if err := os.WriteFile(partial, bad, 0600); err != nil {
213新增: t.Fatal(err)
214新增: }
215新增: requests := 0
216新增: server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
217新增: requests++
218新增: if r.Header.Get("Range") != "" {
219新增: t.Error("retried using the oversized prefix")
220新增: }
221新增: _, _ = w.Write(content)
222新增: }))
223新增: defer server.Close()
224新增: transport := &http.Transport{DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
225新增: return new(net.Dialer).DialContext(ctx, network, server.Listener.Addr().String())
226新增: }}
227新增: defer transport.CloseIdleConnections()
228新增: for attempt := 0; attempt < 2; attempt++ {
229新增: ready, err := Prepare(t.Context(), cache, plan, io.Discard, transport)
230新增: if err != nil || ready.Digest != plan.Digest || ready.Path != plan.CachedPath(cache) {
231新增: t.Fatalf("retry did not prepare the original image: %+v %v", ready, err)
232新增: }
233新增: }
234新增: retained, err := filepath.Glob(partial + ".invalid-*")
235新增: if err != nil || len(retained) != 1 || requests != 1 {
236新增: t.Fatalf("retained=%v requests=%d error=%v", retained, requests, err)
237新增: }
238新增: data, err := os.ReadFile(retained[0])
239新增: if err != nil || !bytes.Equal(data, bad) {
240新增: t.Fatal("discarded the failed response", err)
241新增: }
242新增:}
243新增:
244新增:// Opt-in integration uses a caller-created private directory. It never boots
245新增:// a VM or reads a user's personal data. Media downloads require a second opt-in.
246新增:func TestLiveHostSource(t *testing.T) {
247新增: dir := os.Getenv("CAGE_TEST_HOST_SOURCE")
248新增: if dir == "" {
249新增: t.Skip("set CAGE_TEST_HOST_SOURCE to a private test directory")
250新增: }
251新增: if !filepath.IsAbs(dir) {
252新增: t.Fatal("absolute test directory required")
253新增: }
254新增: host, err := Host(context.Background())
255新增: if err != nil {
256新增: t.Fatal(err)
257新增: }
258新增: if IsLinux(host.System) {
259新增: t.Skip("Linux live source uses bundled template through the workbench")
260新增: }
261新增: var transport *http.Transport
262新增: if config := os.Getenv("CAGE_TEST_HOST_CONFIG"); config != "" {
263新增: cfg, err := cage.Load(config)
264新增: if err != nil {
265新增: t.Fatal(err)
266新增: }
267新增: egress, err := cage.NewEgress(cfg)
268新增: if err != nil {
269新增: t.Fatal(err)
270新增: }
271新增: transport = &http.Transport{Proxy: nil, DialContext: egress.DialContext}
272新增: defer transport.CloseIdleConnections()
273新增: }
274新增: var roundTripper http.RoundTripper
275新增: if transport != nil {
276新增: roundTripper = transport
277新增: }
278新增: plan, err := Resolve(t.Context(), host, dir, dir, nil, roundTripper)
279新增: if err != nil {
280新增: t.Fatal(err)
281新增: }
282新增: data, _ := json.MarshalIndent(plan, "", " ")
283新增: t.Log(runtime.GOOS, string(data))
284新增: if err = os.WriteFile(filepath.Join(dir, "plan.json"), data, 0600); err != nil {
285新增: t.Fatal(err)
286新增: }
287新增: if os.Getenv("CAGE_TEST_HOST_SOURCE_DOWNLOAD") != "1" {
288新增: return
289新增: }
290新增: plan, err = Prepare(t.Context(), dir, plan, os.Stdout, roundTripper)
291新增: if err != nil {
292新增: t.Fatal(err)
293新增: }
294新增: data, _ = json.MarshalIndent(plan, "", " ")
295新增: if err = os.WriteFile(filepath.Join(dir, "plan.json"), data, 0600); err != nil {
296新增: t.Fatal(err)
297新增: }
298新增:}
新增internal/hostimage/ubuntu_test.go+71 −0看文件
@@ -0,0 +1,71 @@
1新增:package hostimage_test
2新增:
3新增:import (
4新增: "context"
5新增: "encoding/json"
6新增: "os"
7新增: "path/filepath"
8新增: "strings"
9新增: "testing"
10新增:
11新增: "github.com/sylvinus/agent-vm/internal/hostimage"
12新增: "github.com/sylvinus/agent-vm/internal/limaembed"
13新增:)
14新增:
15新增:func TestUbuntu2204PinnedImageAndPersistentTemplate(t *testing.T) {
16新增: template, err := limaembed.ReadImageTemplate("ubuntu-22.04")
17新增: if err != nil {
18新增: t.Fatal(err)
19新增: }
20新增: identity := hostimage.Identity{System: "ubuntu-22.04", Version: "22.04", Arch: "amd64"}
21新增: state := t.TempDir()
22新增: plan, err := hostimage.Resolve(context.Background(), identity, state, t.TempDir(), template, nil)
23新增: if err != nil || !strings.Contains(plan.URL, "/jammy/release-20261106/") || len(plan.Digest) != 71 {
24新增: t.Fatalf("source: %+v %v", plan, err)
25新增: }
26新增: plan.Path = filepath.Join(state, "ubuntu.img")
27新增: if err := hostimage.WriteLinuxTemplate(state, plan); err != nil {
28新增: t.Fatal(err)
29新增: }
30新增: saved, err := hostimage.Load(filepath.Join(state, "guest-media"))
31新增: if err != nil || saved != plan {
32新增: t.Fatalf("persistent media: %+v %v", saved, err)
33新增: }
34新增: path, err := hostimage.LinuxTemplate(state)
35新增: if err != nil {
36新增: t.Fatal(err)
37新增: }
38新增: data, err := os.ReadFile(path)
39新增: var config struct{ Images []map[string]string }
40新增: if err != nil || json.Unmarshal(data, &config) != nil || len(config.Images) != 1 || config.Images[0]["location"] != plan.Path {
41新增: t.Fatalf("template changed source or added fallbacks: %s %v", data, err)
42新增: }
43新增: plan.URL = "https://cloud-images.ubuntu.com.evil.test/ubuntu.img"
44新增: if err := plan.Validate(); err == nil {
45新增: t.Fatal("accepted an untrusted Ubuntu image source")
46新增: }
47新增:}
48新增:
49新增:func TestUbuntuChoiceNeverFallsBackAfterMetadataLoss(t *testing.T) {
50新增: for _, removed := range []string{"host-system.yaml", "host-system-source.json"} {
51新增: state := t.TempDir()
52新增: template, _ := limaembed.ReadImageTemplate("ubuntu-22.04")
53新增: plan, err := hostimage.Resolve(t.Context(), hostimage.Identity{System: "ubuntu-22.04", Version: "22.04", Arch: "arm64"}, state, state, template, nil)
54新增: if err != nil {
55新增: t.Fatal(err)
56新增: }
57新增: plan.Path = filepath.Join(state, "ubuntu.img")
58新增: if err := hostimage.WriteLinuxTemplate(state, plan); err != nil {
59新增: t.Fatal(err)
60新增: }
61新增: if system, err := hostimage.LinuxSystem(state); err != nil || system != "ubuntu-22.04" {
62新增: t.Fatalf("identity: %q %v", system, err)
63新增: }
64新增: if err := os.Remove(filepath.Join(state, "guest-media", removed)); err != nil {
65新增: t.Fatal(err)
66新增: }
67新增: if _, err := hostimage.LinuxTemplate(state); err == nil {
68新增: t.Fatalf("silently fell back after losing %s", removed)
69新增: }
70新增: }
71新增:}
新增internal/hostimage/windows_catalog.go+118 −0看文件
@@ -0,0 +1,118 @@
1新增:package hostimage
2新增:
3新增:import (
4新增: "bytes"
5新增: "context"
6新增: "crypto/sha256"
7新增: "encoding/base64"
8新增: "encoding/json"
9新增: "encoding/xml"
10新增: "errors"
11新增: "fmt"
12新增: "io"
13新增: "net/http"
14新增: "net/url"
15新增: "strings"
16新增: "time"
17新增:)
18新增:
19新增:// The Microsoft service publishes a SHA-256-authenticated CAB containing the
20新增:// current MCT catalog. Discovery sends only the OS build and architecture.
21新增:func currentWindowsCatalog(ctx context.Context, client *http.Client, host Identity) (windowsMediaCatalog, error) {
22新增: ctx, cancel := context.WithTimeout(ctx, 12*time.Second)
23新增: defer cancel()
24新增: var catalog windowsMediaCatalog
25新增: body, _ := json.Marshal(map[string]string{
26新增: "Products": "PN=Windows.Products.Cab.amd64&V=0.0.0.0",
27新增: "DeviceAttributes": "DUScan=1;OSVersion=10.0." + host.Build,
28新增: })
29新增: request, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://fe3.delivery.mp.microsoft.com/UpdateMetadataService/updates/search/v1/bydeviceinfo", bytes.NewReader(body))
30新增: if err != nil {
31新增: return catalog, err
32新增: }
33新增: request.Header.Set("Content-Type", "application/json")
34新增: request.Header.Set("Accept", "*/*")
35新增: request.Header.Set("User-Agent", "Mozilla/5.0 (compatible; Cage-SystemInstaller/1.0)")
36新增: data, err := catalogResponse(client, request)
37新增: if err != nil {
38新增: return catalog, err
39新增: }
40新增: var records []json.RawMessage
41新增: trimmed := bytes.TrimSpace(data)
42新增: if len(trimmed) > 0 && trimmed[0] == '[' {
43新增: if err = json.Unmarshal(trimmed, &records); err != nil {
44新增: return catalog, err
45新增: }
46新增: } else {
47新增: records = []json.RawMessage{trimmed}
48新增: }
49新增: if len(records) != 1 {
50新增: return catalog, errors.New("微软目录更新返回多个结果")
51新增: }
52新增: var update struct {
53新增: Files []struct {
54新增: Name string `json:"FileName"`
55新增: URL string `json:"Url"`
56新增: Digest string `json:"Digest"`
57新增: Size json.Number `json:"Size"`
58新增: } `json:"FileLocations"`
59新增: }
60新增: if err = json.Unmarshal(records[0], &update); err != nil {
61新增: return catalog, err
62新增: }
63新增: for _, file := range update.Files {
64新增: if file.Name != "products.cab" {
65新增: continue
66新增: }
67新增: address, err := url.Parse(file.URL)
68新增: if err != nil || address.User != nil || address.Port() != "" || address.Fragment != "" ||
69新增: (address.Scheme != "https" && address.Scheme != "http") ||
70新增: !(strings.HasSuffix(address.Hostname(), ".delivery.mp.microsoft.com") || address.Hostname() == "download.microsoft.com" || address.Hostname() == "download.windowsupdate.com") {
71新增: return catalog, errors.New("微软目录更新地址无法核验")
72新增: }
73新增: digest, err := base64.StdEncoding.DecodeString(file.Digest)
74新增: size, sizeErr := file.Size.Int64()
75新增: if err != nil || sizeErr != nil || len(digest) != sha256.Size || size <= 0 || size > 8<<20 {
76新增: return catalog, errors.New("微软目录更新摘要或大小无效")
77新增: }
78新增: request, err := http.NewRequestWithContext(ctx, http.MethodGet, file.URL, nil)
79新增: if err != nil {
80新增: return catalog, err
81新增: }
82新增: request.Header.Set("User-Agent", "Mozilla/5.0 (compatible; Cage-SystemInstaller/1.0)")
83新增: compressed, err := catalogResponse(client, request)
84新增: if err != nil {
85新增: return catalog, err
86新增: }
87新增: actual := sha256.Sum256(compressed)
88新增: if int64(len(compressed)) != size || !bytes.Equal(actual[:], digest) {
89新增: return catalog, errors.New("微软目录更新校验失败")
90新增: }
91新增: data, err := expandWindowsCatalog(ctx, compressed)
92新增: if err != nil {
93新增: return catalog, err
94新增: }
95新增: err = xml.Unmarshal(data, &catalog)
96新增: return catalog, err
97新增: }
98新增: return catalog, errors.New("微软尚未提供当前系统的安装目录")
99新增:}
100新增:
101新增:func catalogResponse(client *http.Client, request *http.Request) ([]byte, error) {
102新增: response, err := client.Do(request)
103新增: if err != nil {
104新增: return nil, err
105新增: }
106新增: defer response.Body.Close()
107新增: if response.StatusCode != http.StatusOK {
108新增: return nil, fmt.Errorf("微软目录返回 HTTP %d", response.StatusCode)
109新增: }
110新增: data, err := io.ReadAll(io.LimitReader(response.Body, (8<<20)+1))
111新增: if err != nil {
112新增: return nil, err
113新增: }
114新增: if len(data) > 8<<20 {
115新增: return nil, errors.New("微软目录超过大小限制")
116新增: }
117新增: return data, nil
118新增:}
新增internal/keepawake/keepawake.go+50 −0看文件
@@ -0,0 +1,50 @@
1新增:// Package keepawake holds a host power request without keeping its display on.
2新增:package keepawake
3新增:
4新增:import (
5新增: "context"
6新增: "time"
7新增:)
8新增:
9新增:type State struct {
10新增: Active bool `json:"active"`
11新增: Error string `json:"error,omitempty"`
12新增:}
13新增:
14新增:// Run owns the request until ctx ends, including time between phone connections.
15新增:// A failed or unexpectedly exited helper is reported and retried. The caller
16新增:// must wait for Run to return when shutting down its hosting service.
17新增:func Run(ctx context.Context, report func(State)) {
18新增: run(ctx, report, hold)
19新增:}
20新增:
21新增:func run(ctx context.Context, report func(State), acquire func(context.Context, func()) error) {
22新增: var previous State
23新增: emit := func(state State) {
24新增: if state != previous {
25新增: previous = state
26新增: report(state)
27新增: }
28新增: }
29新增: delay := time.Second
30新增: defer emit(State{})
31新增: for ctx.Err() == nil {
32新增: err := acquire(ctx, func() { emit(State{Active: true}); delay = time.Second })
33新增: if ctx.Err() != nil {
34新增: return
35新增: }
36新增: message := "主机防休眠请求已结束"
37新增: if err != nil {
38新增: message = err.Error()
39新增: }
40新增: emit(State{Error: message})
41新增: timer := time.NewTimer(delay)
42新增: select {
43新增: case <-ctx.Done():
44新增: timer.Stop()
45新增: return
46新增: case <-timer.C:
47新增: }
48新增: delay = min(30*time.Second, delay*2)
49新增: }
50新增:}
新增internal/keepawake/keepawake_darwin.go+7 −0看文件
@@ -0,0 +1,7 @@
1新增:package keepawake
2新增:
3新增:import "context"
4新增:
5新增:func hold(ctx context.Context, ready func()) error {
6新增: return holdProcess(ctx, ready, "/usr/bin/caffeinate", "-i", "/bin/sh", "-c", waitForHost)
7新增:}
新增internal/keepawake/keepawake_darwin_test.go+74 −0看文件
@@ -0,0 +1,74 @@
1新增:package keepawake
2新增:
3新增:import (
4新增: "context"
5新增: "os"
6新增: "os/exec"
7新增: "regexp"
8新增: "strconv"
9新增: "strings"
10新增: "testing"
11新增: "time"
12新增:)
13新增:
14新增:func TestMacNativePowerRequest(t *testing.T) {
15新增: ctx, cancel := context.WithCancel(context.Background())
16新增: defer cancel()
17新增: ready := make(chan struct{})
18新增: done := make(chan error, 1)
19新增: go func() { done <- hold(ctx, func() { close(ready) }) }()
20新增: select {
21新增: case <-ready:
22新增: case err := <-done:
23新增: t.Fatal("power request failed", err)
24新增: case <-time.After(6 * time.Second):
25新增: t.Fatal("power request did not start")
26新增: }
27新增: owned := func(pid int) bool {
28新增: for i := 0; i < 8 && pid > 1; i++ {
29新增: if pid == os.Getpid() {
30新增: return true
31新增: }
32新增: value, err := exec.Command("/bin/ps", "-o", "ppid=", "-p", strconv.Itoa(pid)).Output()
33新增: if err != nil {
34新增: return false
35新增: }
36新增: pid, _ = strconv.Atoi(strings.TrimSpace(string(value)))
37新增: }
38新增: return false
39新增: }
40新增: pattern := regexp.MustCompile(`pid ([0-9]+)\(caffeinate\):[^\n]+`)
41新增: var assertionPID string
42新增: deadline := time.Now().Add(3 * time.Second)
43新增: for time.Now().Before(deadline) && assertionPID == "" {
44新增: data, err := exec.Command("/usr/bin/pmset", "-g", "assertions").Output()
45新增: if err != nil {
46新增: t.Fatal(err)
47新增: }
48新增: for _, match := range pattern.FindAllStringSubmatch(string(data), -1) {
49新增: pid, _ := strconv.Atoi(match[1])
50新增: if owned(pid) {
51新增: if !strings.Contains(match[0], "PreventUserIdleSystemSleep") || strings.Contains(match[0], "PreventUserIdleDisplaySleep") {
52新增: t.Fatal("wrong assertion", match[0])
53新增: }
54新增: assertionPID = match[1]
55新增: }
56新增: }
57新增: if assertionPID == "" {
58新增: time.Sleep(50 * time.Millisecond)
59新增: }
60新增: }
61新增: if assertionPID == "" {
62新增: t.Fatal("no owned idle-system-sleep assertion found")
63新增: }
64新增: cancel()
65新增: select {
66新增: case <-done:
67新增: case <-time.After(3 * time.Second):
68新增: t.Fatal("power helper did not exit")
69新增: }
70新增: data, err := exec.Command("/usr/bin/pmset", "-g", "assertions").Output()
71新增: if err != nil || strings.Contains(string(data), "pid "+assertionPID+"(caffeinate):") {
72新增: t.Fatal("power assertion survived cancellation", err)
73新增: }
74新增:}
新增internal/keepawake/keepawake_linux.go+7 −0看文件
@@ -0,0 +1,7 @@
1新增:package keepawake
2新增:
3新增:import "context"
4新增:
5新增:func hold(ctx context.Context, ready func()) error {
6新增: return holdProcess(ctx, ready, "/usr/bin/systemd-inhibit", "--what=sleep", "--mode=block", "--who=Cage", "--why=Cage remote access", "--no-ask-password", "/bin/sh", "-c", waitForHost)
7新增:}
新增internal/keepawake/keepawake_test.go+60 −0看文件
@@ -0,0 +1,60 @@
1新增:package keepawake
2新增:
3新增:import (
4新增: "context"
5新增: "errors"
6新增: "testing"
7新增: "time"
8新增:)
9新增:
10新增:func TestRetryAndRelease(t *testing.T) {
11新增: ctx, cancel := context.WithCancel(context.Background())
12新增: defer cancel()
13新增: states := make(chan State, 8)
14新增: done := make(chan struct{})
15新增: released := make(chan struct{})
16新增: attempts := 0
17新增: go func() {
18新增: defer close(done)
19新增: run(ctx, func(state State) { states <- state }, func(ctx context.Context, ready func()) error {
20新增: attempts++
21新增: if attempts == 1 {
22新增: return errors.New("inhibitor unavailable")
23新增: }
24新增: ready()
25新增: <-ctx.Done()
26新增: close(released)
27新增: return ctx.Err()
28新增: })
29新增: }()
30新增: read := func() State {
31新增: t.Helper()
32新增: select {
33新增: case state := <-states:
34新增: return state
35新增: case <-time.After(3 * time.Second):
36新增: t.Fatal("missing power request state")
37新增: return State{}
38新增: }
39新增: }
40新增: if state := read(); state.Active || state.Error == "" {
41新增: t.Fatal("failed request was hidden", state)
42新增: }
43新增: if state := read(); !state.Active || state.Error != "" {
44新增: t.Fatal("request did not recover", state)
45新增: }
46新增: cancel()
47新增: select {
48新增: case <-done:
49新增: case <-time.After(time.Second):
50新增: t.Fatal("request leaked after cancellation")
51新增: }
52新增: select {
53新增: case <-released:
54新增: default:
55新增: t.Fatal("native request was not released")
56新增: }
57新增: if state := read(); state != (State{}) {
58新增: t.Fatal("stopped request remained active", state)
59新增: }
60新增:}
新增internal/keepawake/keepawake_windows.go+49 −0看文件
@@ -0,0 +1,49 @@
1新增:package keepawake
2新增:
3新增:import (
4新增: "context"
5新增: "fmt"
6新增: "runtime"
7新增: "unsafe"
8新增:
9新增: "golang.org/x/sys/windows"
10新增:)
11新增:
12新增:var powerLibrary = windows.NewLazySystemDLL("kernel32.dll")
13新增:var powerCreate = powerLibrary.NewProc("PowerCreateRequest")
14新增:var powerSet = powerLibrary.NewProc("PowerSetRequest")
15新增:var powerClear = powerLibrary.NewProc("PowerClearRequest")
16新增:
17新增:// Match REASON_CONTEXT's full union layout, including its detailed variant.
18新增:type reasonContext struct {
19新增: Version, Flags uint32
20新增: SimpleReason uintptr
21新增: ResourceID, StringCount uint32
22新增: Strings uintptr
23新增:}
24新增:
25新增:func hold(ctx context.Context, ready func()) error {
26新增: reason, err := windows.UTF16PtrFromString("Cage 远程连接待机")
27新增: if err != nil {
28新增: return err
29新增: }
30新增: value := reasonContext{Flags: 1, SimpleReason: uintptr(unsafe.Pointer(reason))}
31新增: handle, _, callErr := powerCreate.Call(uintptr(unsafe.Pointer(&value)))
32新增: runtime.KeepAlive(reason)
33新增: if handle == ^uintptr(0) || handle == 0 {
34新增: return fmt.Errorf("无法创建主机防休眠请求:%w", callErr)
35新增: }
36新增: defer windows.CloseHandle(windows.Handle(handle))
37新增: // POWER_REQUEST_TYPE: SystemRequired=1, ExecutionRequired=3. No display or
38新增: // away-mode request: monitors can sleep and explicit user sleep is respected.
39新增: for _, kind := range []uintptr{1, 3} {
40新增: ok, _, err := powerSet.Call(handle, kind)
41新增: if ok == 0 {
42新增: return fmt.Errorf("无法启用主机防休眠请求:%w", err)
43新增: }
44新增: defer powerClear.Call(handle, kind)
45新增: }
46新增: ready()
47新增: <-ctx.Done()
48新增: return ctx.Err()
49新增:}
新增internal/keepawake/process.go+76 −0看文件
@@ -0,0 +1,76 @@
1新增://go:build darwin || linux
2新增:
3新增:package keepawake
4新增:
5新增:import (
6新增: "bufio"
7新增: "bytes"
8新增: "context"
9新增: "errors"
10新增: "os/exec"
11新增: "strings"
12新增: "time"
13新增:)
14新增:
15新增:// The child acknowledges startup only after the inhibitor utility launches it.
16新增:// Closing stdin ends the shell's builtin read, so no orphaned sleep process or
17新增:// permanent system setting remains after the hosting service exits.
18新增:const waitForHost = `printf 'ready\n'; read -r cage_remote_wait`
19新增:
20新增:func holdProcess(ctx context.Context, ready func(), command string, args ...string) error {
21新增: cmd := exec.Command(command, args...)
22新增: cmd.WaitDelay = 2 * time.Second
23新增: stdin, err := cmd.StdinPipe()
24新增: if err != nil {
25新增: return err
26新增: }
27新增: defer stdin.Close()
28新增: stdout, err := cmd.StdoutPipe()
29新增: if err != nil {
30新增: return err
31新增: }
32新增: var stderr bytes.Buffer
33新增: cmd.Stderr = &stderr
34新增: if err := cmd.Start(); err != nil {
35新增: return err
36新增: }
37新增: done := make(chan struct{})
38新增: var waitErr error
39新增: go func() { waitErr = cmd.Wait(); close(done) }()
40新增: finish := func() {
41新增: _ = stdin.Close()
42新增: select {
43新增: case <-done:
44新增: case <-time.After(2 * time.Second):
45新增: _ = cmd.Process.Kill()
46新增: <-done
47新增: }
48新增: }
49新增: defer finish()
50新增: ack := make(chan bool, 1)
51新增: go func() { line, err := bufio.NewReader(stdout).ReadString('\n'); ack <- err == nil && line == "ready\n" }()
52新增: timer := time.NewTimer(5 * time.Second)
53新增: defer timer.Stop()
54新增: select {
55新增: case <-ctx.Done():
56新增: return ctx.Err()
57新增: case <-timer.C:
58新增: return errors.New("主机防休眠请求超时")
59新增: case ok := <-ack:
60新增: if !ok {
61新增: finish()
62新增: message := strings.TrimSpace(stderr.String())
63新增: if len(message) > 512 {
64新增: message = message[:512]
65新增: }
66新增: return errors.New("无法启用主机防休眠:" + message)
67新增: }
68新增: }
69新增: ready()
70新增: select {
71新增: case <-ctx.Done():
72新增: return ctx.Err()
73新增: case <-done:
74新增: return waitErr
75新增: }
76新增:}
修改internal/limaembed/assets/README+3 −3看文件
@@ -1,3 +1,3 @@
1删除:Filled by `make`: Lima's guest agent for this architecture (gzipped) and
2删除:Lima's templates, embedded in agent-vm (see ../share.go). Without them,
3删除:agent-vm builds but cannot create or start a VM.
1新增:The Makefile places Lima's templates and the gzipped Linux guest agent here.
2新增:Apple Silicon builds also place the macOS guest agent in Darwin/. Other builds
3新增:exclude that directory. See ../share.go for extraction and guest selection.
新增internal/limaembed/assets_darwin_arm64.go+6 −0看文件
@@ -0,0 +1,6 @@
1新增:package limaembed
2新增:
3新增:import "embed"
4新增:
5新增://go:embed all:assets
6新增:var assets embed.FS
新增internal/limaembed/assets_other.go+10 −0看文件
@@ -0,0 +1,10 @@
1新增://go:build !darwin || !arm64
2新增:
3新增:package limaembed
4新增:
5新增:import "embed"
6新增:
7新增:// Exclude the Darwin directory even when cross-compiling in a Mac checkout.
8新增://
9新增://go:embed all:assets/[^D]*
10新增:var assets embed.FS
新增internal/limaembed/host-images/ubuntu-22.04.yaml+11 −0看文件
@@ -0,0 +1,11 @@
1新增:# Canonical Jammy release-20261106, verified against its published SHA256SUMS.
2新增:# Keep this outside generated Lima assets so `make assets` preserves the pin.
3新增:images:
4新增:- location: "https://cloud-images.ubuntu.com/releases/jammy/release-20261106/ubuntu-22.04-server-cloudimg-amd64.img"
5新增: arch: "x86_64"
6新增: digest: "sha256:f77bc6d59cb8deaa9657095736b5f5003f7705b47055f01823459715c967de6a"
7新增: bytes: 730617344
8新增:- location: "https://cloud-images.ubuntu.com/releases/jammy/release-20261106/ubuntu-22.04-server-cloudimg-arm64.img"
9新增: arch: "aarch64"
10新增: digest: "sha256:7fc0212296c65f8e20f8e9af89aaab9500ea4ec73cfb245afa0f2b509bb90785"
11新增: bytes: 701041664
修改internal/limaembed/limaembed.go+10 −0看文件
@@ -28,6 +28,7 @@ import (
2828 "github.com/sylvinus/agent-vm/internal/cage"
2929 "github.com/sylvinus/agent-vm/internal/diagnostics"
3030 "github.com/sylvinus/agent-vm/internal/guard"
31新增: "github.com/sylvinus/agent-vm/internal/guestos"
3132 "github.com/sylvinus/agent-vm/internal/netguard"
3233 "github.com/sylvinus/agent-vm/internal/state"
3334 "github.com/sylvinus/agent-vm/internal/vmname"
@@ -116,6 +117,15 @@ func Run(args []string) bool {
116117 if stopGateControl, err = cage.StartGateControl(path, filepath.Join(string(st), "lima", name), gate); err != nil {
117118 logrus.Fatal(err)
118119 }
120新增: if name == "mac" {
121新增: // The installed Mac profile binds this exact VZ instance. Other
122新增: // workloads retain their existing switch behavior.
123新增: if binding, err := guestos.LoadMacOSProfile(filepath.Dir(path)); err != nil {
124新增: logrus.Fatal(err)
125新增: } else if binding != nil && binding.Instance == name {
126新增: usernet.DroppedIPv6 = gate.ObserveDroppedIPv6
127新增: }
128新增: }
119129 usernet.Outbound, usernet.GuestDial = gate.Allows, gate.DialContext
120130 usernet.DNSExchange, dns.Exchange = gate.ExchangeDNS, gate.ExchangeDNS
121131 }
修改internal/limaembed/share.go+49 −21看文件
@@ -2,7 +2,7 @@ package limaembed
22
33import (
44 "crypto/sha256"
5删除: "embed"
5新增: _ "embed"
66 "errors"
77 "fmt"
88 "io/fs"
@@ -12,19 +12,28 @@ import (
1212 "strings"
1313)
1414
15删除:// What Lima finds in <prefix>/share/lima next to limactl: the guest agent and
16删除:// the templates. Put in by the Makefile; see assets/README.
17删除://
18删除://go:embed all:assets
19删除:var assets embed.FS
20删除:
2115// Share is Lima's share/lima, written out of the binary.
2216type Share struct {
23删除: // Dir holds templates/ and the guest agent.
24删除: Dir string
25删除: // GuestAgent is the guest agent for Linux guests of this host's
26删除: // architecture, gzipped: Lima decompresses it.
27删除: GuestAgent string
17新增: // Dir holds templates/ and the bundled guest agents.
18新增: Dir string
19新增: guestAgents map[string]string
20新增:}
21新增:
22新增:// Cage owns this pin independently of Lima's periodically regenerated templates.
23新增://
24新增://go:embed host-images/ubuntu-22.04.yaml
25新增:var ubuntu2204Image []byte
26新增:
27新增:// ReadImageTemplate returns the pinned images bundled with this application.
28新增:func ReadImageTemplate(system string) ([]byte, error) {
29新增: switch system {
30新增: case "ubuntu-22.04":
31新增: return ubuntu2204Image, nil
32新增: case "debian-12", "debian-13", "ubuntu-24.04":
33新增: return fs.ReadFile(assets, "assets/templates/_images/"+system+".yaml")
34新增: default:
35新增: return nil, fmt.Errorf("unsupported host image template %q", system)
36新增: }
2837}
2938
3039// Templates is where Lima reads templates from (LIMA_TEMPLATES_PATH).
@@ -32,6 +41,16 @@ func (s *Share) Templates() string {
3241 return filepath.Join(s.Dir, "templates")
3342}
3443
44新增:// GuestAgent returns only helpers that were extracted from this executable.
45新增:// An older installation may have left other binaries in the same directory.
46新增:func (s *Share) GuestAgent(guestOS, arch string) (string, error) {
47新增: name := "lima-guestagent." + guestOS + "-" + arch + ".gz"
48新增: if agent, ok := s.guestAgents[name]; ok {
49新增: return agent, nil
50新增: }
51新增: return "", fmt.Errorf("this build does not include the Lima guest agent for %s/%s", guestOS, arch)
52新增:}
53新增:
3554// ErrNoAssets is returned by WriteShare when agent-vm was built without
3655// the guest agent (`go build` instead of `make`).
3756var ErrNoAssets = errors.New("this agent-vm was built without Lima's guest agent: build it with make")
@@ -40,12 +59,15 @@ var ErrNoAssets = errors.New("this agent-vm was built without Lima's guest agent
4059// missing or differs from the embedded copy, and returns where they are. The
4160// files are checked on every call: a damaged guest agent never reaches a VM.
4261func WriteShare(dir string) (*Share, error) {
43删除: agent := "lima-guestagent.Linux-" + guestArch() + ".gz"
44删除: if _, err := fs.Stat(assets, "assets/"+agent); err != nil {
62新增: return writeShare(dir, assets)
63新增:}
64新增:
65新增:func writeShare(dir string, files fs.FS) (*Share, error) {
66新增: if _, err := fs.Stat(files, "assets/lima-guestagent.Linux-"+guestArch()+".gz"); err != nil {
4567 return nil, ErrNoAssets
4668 }
47删除: share := filepath.Join(dir, "share", "lima")
48删除: err := fs.WalkDir(assets, "assets", func(p string, d fs.DirEntry, err error) error {
69新增: share := &Share{Dir: filepath.Join(dir, "share", "lima"), guestAgents: make(map[string]string)}
70新增: err := fs.WalkDir(files, "assets", func(p string, d fs.DirEntry, err error) error {
4971 if err != nil {
5072 return err
5173 }
@@ -53,20 +75,26 @@ func WriteShare(dir string) (*Share, error) {
5375 if rel == "README" {
5476 return nil
5577 }
56删除: dst := filepath.Join(share, filepath.FromSlash(rel))
78新增: dst := filepath.Join(share.Dir, filepath.FromSlash(rel))
5779 if d.IsDir() {
5880 return os.MkdirAll(dst, 0o700)
5981 }
60删除: want, err := assets.ReadFile(p)
82新增: want, err := fs.ReadFile(files, p)
6183 if err != nil {
6284 return err
6385 }
64删除: return writeIfChanged(dst, want)
86新增: if err := writeIfChanged(dst, want); err != nil {
87新增: return err
88新增: }
89新增: if strings.HasPrefix(d.Name(), "lima-guestagent.") && strings.HasSuffix(d.Name(), ".gz") {
90新增: share.guestAgents[d.Name()] = dst
91新增: }
92新增: return nil
6593 })
6694 if err != nil {
67删除: return nil, fmt.Errorf("writing Lima's files to %s: %w", share, err)
95新增: return nil, fmt.Errorf("writing Lima's files to %s: %w", share.Dir, err)
6896 }
69删除: return &Share{Dir: share, GuestAgent: filepath.Join(share, agent)}, nil
97新增: return share, nil
7098}
7199
72100func writeIfChanged(dst string, want []byte) error {
新增internal/limaembed/share_test.go+47 −0看文件
@@ -0,0 +1,47 @@
1新增:package limaembed
2新增:
3新增:import (
4新增: "os"
5新增: "testing"
6新增: "testing/fstest"
7新增:)
8新增:
9新增:func TestGuestAgentMatchesGuestAndCurrentBuild(t *testing.T) {
10新增: linuxArch := guestArch()
11新增: const darwinFile = "assets/Darwin/lima-guestagent.Darwin-aarch64.gz"
12新增: files := fstest.MapFS{
13新增: "assets/lima-guestagent.Linux-" + linuxArch + ".gz": {Data: []byte("linux")},
14新增: darwinFile: {Data: []byte("darwin")},
15新增: }
16新增: dir := t.TempDir()
17新增: share, err := writeShare(dir, files)
18新增: if err != nil {
19新增: t.Fatal(err)
20新增: }
21新增: for _, guest := range []struct{ os, arch, data string }{
22新增: {"Linux", linuxArch, "linux"},
23新增: {"Darwin", "aarch64", "darwin"},
24新增: } {
25新增: path, err := share.GuestAgent(guest.os, guest.arch)
26新增: if err != nil {
27新增: t.Fatal(err)
28新增: }
29新增: data, err := os.ReadFile(path)
30新增: if err != nil || string(data) != guest.data {
31新增: t.Fatalf("%s/%s: read %q, %v", guest.os, guest.arch, data, err)
32新增: }
33新增: }
34新增: if path, err := share.GuestAgent("Darwin", "x86_64"); err == nil {
35新增: t.Fatalf("used %s for an unbundled architecture", path)
36新增: }
37新增:
38新增: // A different build can reuse the same profile with the old file on disk.
39新增: delete(files, darwinFile)
40新增: share, err = writeShare(dir, files)
41新增: if err != nil {
42新增: t.Fatal(err)
43新增: }
44新增: if path, err := share.GuestAgent("Darwin", "aarch64"); err == nil {
45新增: t.Fatalf("used %s after the build stopped bundling it", path)
46新增: }
47新增:}
新增internal/maclogin/bridge.h+9 −0看文件
@@ -0,0 +1,9 @@
1新增:#include <stdbool.h>
2新增:#include <stdlib.h>
3新增:void cageLoginLoop(void *machine);
4新增:void cageLoginStop(void);
5新增:void cageLoginEnable(bool enabled);
6新增:void *cageLoginImage(int *size);
7新增:bool cageLoginClick(int x, int y);
8新增:bool cageLoginScroll(int x, int y, int deltaX, int deltaY);
9新增:bool cageLoginKey(int code, bool shift);
新增internal/maclogin/bridge_darwin.m+84 −0看文件
@@ -0,0 +1,84 @@
1新增://go:build darwin && arm64 && cgo && !no_vz
2新增:#import <Cocoa/Cocoa.h>
3新增:#import <IOKit/hidsystem/IOLLEvent.h>
4新增:#import "bridge.h"
5新增:#import "../../scripts/guest-os/macos-setup-view.m"
6新增:
7新增:static VZVirtualMachine *machine;
8新增:static CageGuestSetupView *loginView;
9新增:// Match the virtual Mac's scanout. The input protocol retains its original
10新增:// 16:10 coordinate system, regardless of host window size or display scaling.
11新增:static const CGFloat scanWidth = 1920, scanHeight = 1200;
12新增:
13新增:void cageLoginLoop(void *ref) {
14新增: @autoreleasepool {
15新增: machine = (__bridge VZVirtualMachine *)ref;
16新增: NSApplication *app = [NSApplication sharedApplication];
17新增: [app setActivationPolicy:NSApplicationActivationPolicyProhibited];
18新增: [app run];
19新增: [loginView close]; loginView = nil; machine = nil;
20新增: }
21新增:}
22新增:void cageLoginStop(void) {
23新增: dispatch_async(dispatch_get_main_queue(), ^{
24新增: [NSApp stop:nil];
25新增: [NSApp postEvent:[NSEvent otherEventWithType:NSEventTypeApplicationDefined location:NSZeroPoint
26新增: modifierFlags:0 timestamp:0 windowNumber:0 context:nil subtype:0 data1:0 data2:0] atStart:YES];
27新增: });
28新增:}
29新增:void cageLoginEnable(bool enabled) {
30新增: dispatch_sync(dispatch_get_main_queue(), ^{
31新增: [loginView close]; loginView = nil;
32新增: if (enabled && machine) loginView = [[CageGuestSetupView alloc] initWithMachine:machine size:NSMakeSize(scanWidth,scanHeight)
33新增: setupAuthorized:^BOOL { return machine != nil; }];
34新增: });
35新增:}
36新增:void *cageLoginImage(int *size) {
37新增: __block void *copy = NULL;
38新增: dispatch_sync(dispatch_get_main_queue(), ^{
39新增: @autoreleasepool {
40新增: NSData *image = [loginView snapshotJPEG];
41新增: if (image.length && image.length <= (4<<20)) {
42新增: copy = malloc(image.length);
43新增: if (copy) { memcpy(copy, image.bytes, image.length); *size = (int)image.length; }
44新增: }
45新增: }
46新增: });
47新增: return copy;
48新增:}
49新增:bool cageLoginClick(int x, int y) {
50新增: __block BOOL ok = NO;
51新增: dispatch_sync(dispatch_get_main_queue(), ^{ ok = [loginView clickAtX:x * scanWidth / 1024.0 y:y * scanHeight / 640.0]; });
52新增: return ok;
53新增:}
54新增:bool cageLoginKey(int code, bool shift) {
55新增: __block BOOL ok = NO;
56新增: dispatch_sync(dispatch_get_main_queue(), ^{
57新增: if (!loginView) return;
58新增: // A hardware modifier carries both the aggregate flag and the left/right
59新增: // device bit. The offscreen view has no host keyboard state to inherit.
60新增: NSEventModifierFlags flags = shift ? NSEventModifierFlagShift | NX_DEVICELSHIFTKEYMASK : 0;
61新增: NSEvent *(^event)(NSEventType, int, NSEventModifierFlags) = ^NSEvent *(NSEventType kind, int key, NSEventModifierFlags mods) {
62新增: return [NSEvent keyEventWithType:kind location:NSZeroPoint modifierFlags:mods timestamp:NSProcessInfo.processInfo.systemUptime
63新增: windowNumber:0 context:nil characters:@"" charactersIgnoringModifiers:@"" isARepeat:NO keyCode:(unsigned short)key];
64新增: };
65新增: if (shift) {
66新增: [loginView sendKey:event(NSEventTypeFlagsChanged,56,flags)];
67新增: [loginView sendKey:event(NSEventTypeKeyDown,56,flags)];
68新增: }
69新增: ok = [loginView sendKey:event(NSEventTypeKeyDown,code,flags)] && [loginView sendKey:event(NSEventTypeKeyUp,code,flags)];
70新增: if (shift) {
71新增: [loginView sendKey:event(NSEventTypeKeyUp,56,0)];
72新增: [loginView sendKey:event(NSEventTypeFlagsChanged,56,0)];
73新增: }
74新增: });
75新增: return ok;
76新增:}
77新增:bool cageLoginScroll(int x, int y, int deltaX, int deltaY) {
78新增: __block BOOL ok = NO;
79新增: dispatch_sync(dispatch_get_main_queue(), ^{
80新增: ok = [loginView scrollAtX:x * scanWidth / 1024.0 y:y * scanHeight / 640.0
81新增: deltaX:deltaX * scanWidth / 1024.0 deltaY:deltaY * scanHeight / 640.0];
82新增: });
83新增: return ok;
84新增:}
新增internal/maclogin/login_darwin_arm64.go+300 −0看文件
@@ -0,0 +1,300 @@
1新增://go:build darwin && arm64 && cgo && !no_vz
2新增:
3新增:// Package maclogin presents only the Apple login screen of the bound trial VM.
4新增:// The owner of the VZ instance creates its view on the AppKit main thread.
5新增:package maclogin
6新增:
7新增:/*
8新增:#cgo CFLAGS: -x objective-c -fobjc-arc
9新增:#cgo LDFLAGS: -framework AppKit -framework Virtualization
10新增:#include "bridge.h"
11新增:*/
12新增:import "C"
13新增:
14新增:import (
15新增: "bytes"
16新增: "context"
17新增: "crypto/rand"
18新增: "crypto/subtle"
19新增: "encoding/json"
20新增: "errors"
21新增: "io"
22新增: "net"
23新增: "os"
24新增: "os/exec"
25新增: "path/filepath"
26新增: "runtime"
27新增:
28新增: "al.essio.dev/pkg/shellescape"
29新增: "time"
30新增: "unsafe"
31新增:
32新增: apple "github.com/Code-Hex/vz/v3"
33新增: driver "github.com/lima-vm/lima/v2/pkg/driver/vz"
34新增: "github.com/sylvinus/agent-vm/internal/guestos"
35新增:)
36新增:
37新增:type objectReference interface{ CageViewObject() unsafe.Pointer }
38新增:
39新增:func init() {
40新增: if _, built := any((*apple.VirtualMachine)(nil)).(objectReference); !built {
41新增: return
42新增: }
43新增: if len(os.Args) > 1 && (os.Args[1] == "hostagent" || os.Args[1] == "--debug") {
44新增: runtime.LockOSThread()
45新增: }
46新增: driver.OwnsOffscreenView = func(dir string) bool {
47新增: config := os.Getenv("CLAUDE_CAGE_CONFIG")
48新增: if !filepath.IsAbs(config) || !sameGuestDirectory(dir, filepath.Join(filepath.Dir(config), "state", "lima", "mac")) {
49新增: return false
50新增: }
51新增: profile, err := guestos.LoadMacOSProfile(filepath.Dir(config))
52新增: return err == nil && profile != nil
53新增: }
54新增: driver.OffscreenView = run
55新增:}
56新增:
57新增:type request = guestos.MacLoginRequest
58新增:type reply = guestos.MacLoginReply
59新增:
60新增:type loginSession struct {
61新增: profile string
62新增: token string
63新增: expires time.Time
64新增: screenID string
65新增: setup bool
66新增:}
67新增:
68新增:func (s *loginSession) currentScreen() string {
69新增: // Check via the separate provisioning account. Guest development files
70新增: // and the standard user's shell initialization cannot grant this view.
71新增: bound, err := guestos.LoadMacOSProfile(s.profile)
72新增: if err != nil || bound == nil {
73新增: return ""
74新增: }
75新增: if s.setup {
76新增: if bound.SetupID == "" {
77新增: return ""
78新增: }
79新增: return "setup-" + bound.SetupID
80新增: }
81新增: args, err := guestos.MacOSSSHArgs(s.profile, "cage")
82新增: if err != nil {
83新增: return ""
84新增: }
85新增: ctx, cancel := context.WithTimeout(context.Background(), 2500*time.Millisecond)
86新增: defer cancel()
87新增: script := `set -eu
88新增:/usr/bin/pgrep -x loginwindow >/dev/null
89新增:owner=$(/usr/bin/stat -f '%u %Su' /dev/console)
90新增:if [ "$owner" = "0 root" ]; then /usr/bin/printf 'system-login'; exit 0; fi
91新增:uid=$(/usr/bin/id -u ` + shellescape.Quote(bound.User) + `)
92新增:/usr/bin/printf '%s %s\n' "$owner" "$uid"
93新增:/usr/sbin/ioreg -a -d1 -c IORegistryEntry -k IOConsoleUsers -l | /usr/bin/plutil -extract IOConsoleUsers xml1 -o - -`
94新增: cmd := exec.CommandContext(ctx, "/usr/bin/ssh", append(args, "-T", "cage-macos", "--", "exec /bin/sh -c "+shellescape.Quote(script))...)
95新增: cmd.Env = []string{"PATH=/usr/bin:/bin", "LC_ALL=C"}
96新增: reader, err := cmd.StdoutPipe()
97新增: if err != nil || cmd.Start() != nil {
98新增: return ""
99新增: }
100新增: b, readErr := io.ReadAll(io.LimitReader(reader, (32<<10)+1))
101新增: if readErr != nil || len(b) > 32<<10 {
102新增: cancel()
103新增: }
104新增: if err = cmd.Wait(); err != nil || readErr != nil || len(b) > 32<<10 {
105新增: return ""
106新增: }
107新增: return permittedLoginScreen(bytes.TrimSpace(b), bound.User)
108新增:}
109新增:
110新增:func (s *loginSession) close() {
111新增: if s.token != "" {
112新增: C.cageLoginEnable(false)
113新增: }
114新增: s.token = ""
115新增: s.screenID = ""
116新增: s.setup = false
117新增:}
118新增:
119新增:func (s *loginSession) handle(in request) reply {
120新增: if in.Action == "finish" && in.Setup {
121新增: bound, err := guestos.LoadMacOSProfile(s.profile)
122新增: if err != nil || bound == nil || bound.SetupID == "" {
123新增: return reply{Closed: true}
124新增: }
125新增: s.close()
126新增: if err = guestos.FinishMacOSSetup(s.profile, bound.SetupID); err != nil {
127新增: return reply{Error: "未能保存首次设置,请重试"}
128新增: }
129新增: return reply{Closed: true}
130新增: }
131新增: if in.Action == "open" {
132新增: s.close()
133新增: s.setup = in.Setup
134新增: s.screenID = s.currentScreen()
135新增: if s.screenID == "" {
136新增: return reply{Error: "客机已解锁,或尚未进入系统登录画面。"}
137新增: }
138新增: s.token = rand.Text()
139新增: s.expires = time.Now().Add(2 * time.Minute)
140新增: if s.setup {
141新增: s.expires = time.Now().Add(15 * time.Minute)
142新增: }
143新增: C.cageLoginEnable(true)
144新增: return reply{Session: s.token}
145新增: }
146新增: if s.token == "" || s.setup != in.Setup || subtle.ConstantTimeCompare([]byte(in.Session), []byte(s.token)) != 1 {
147新增: return reply{Closed: true}
148新增: }
149新增: if time.Now().After(s.expires) || in.Action == "close" || s.currentScreen() != s.screenID {
150新增: s.close()
151新增: return reply{Closed: true}
152新增: }
153新增: switch in.Action {
154新增: case "fill-password":
155新增: sequence, valid := passwordKeys(in.Password)
156新增: if !s.setup || !valid || !s.authorizationDialog() {
157新增: return reply{Error: "请先打开系统授权对话框,并选中密码输入框"}
158新增: }
159新增: for _, key := range sequence {
160新增: if !bool(C.cageLoginKey(C.int(key.code), C.bool(key.shift))) {
161新增: return reply{Error: "授权密码未能填写,请重试"}
162新增: }
163新增: }
164新增: case "frame":
165新增: var n C.int
166新增: p := C.cageLoginImage(&n)
167新增: if p == nil {
168新增: return reply{Error: "尚未收到 Apple 登录画面"}
169新增: }
170新增: defer C.free(p)
171新增: if s.currentScreen() != s.screenID {
172新增: s.close()
173新增: return reply{Closed: true}
174新增: }
175新增: return reply{Image: C.GoBytes(p, n), MIME: "image/jpeg"}
176新增: case "click":
177新增: if in.X < 0 || in.Y < 0 || in.X >= 1024 || in.Y >= 640 || !bool(C.cageLoginClick(C.int(in.X), C.int(in.Y))) {
178新增: return reply{Error: "无效的登录位置"}
179新增: }
180新增: case "key":
181新增: // ANSI printable keys, Return, Tab, Escape and Backspace. No global shortcuts.
182新增: setupNavigation := s.setup && (in.Code >= 123 && in.Code <= 126 || in.Code == 116 || in.Code == 121)
183新增: if in.Code < 0 || (in.Code > 53 && !setupNavigation) || !bool(C.cageLoginKey(C.int(in.Code), C.bool(in.Shift))) {
184新增: return reply{Error: "不支持此登录按键"}
185新增: }
186新增: if in.Code == 36 && !s.setup {
187新增: s.close()
188新增: return reply{Closed: true}
189新增: }
190新增: case "scroll":
191新增: if !s.setup || in.X < 0 || in.Y < 0 || in.X >= 1024 || in.Y >= 640 ||
192新增: in.DeltaX < -512 || in.DeltaX > 512 || in.DeltaY < -512 || in.DeltaY > 512 ||
193新增: !bool(C.cageLoginScroll(C.int(in.X), C.int(in.Y), C.int(in.DeltaX), C.int(in.DeltaY))) {
194新增: return reply{Error: "无效的首次设置滚动操作"}
195新增: }
196新增: default:
197新增: return reply{Error: "未知的登录操作"}
198新增: }
199新增: return reply{}
200新增:}
201新增:
202新增:func (s *loginSession) authorizationDialog() bool {
203新增: ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
204新增: defer cancel()
205新增: bound, err := guestos.LoadMacOSProfile(s.profile)
206新增: if err != nil || bound == nil {
207新增: return false
208新增: }
209新增: args, err := guestos.MacOSSSHArgs(s.profile, bound.User)
210新增: if err != nil {
211新增: return false
212新增: }
213新增: cmd := exec.CommandContext(ctx, "/usr/bin/ssh", append(args, "-T", "cage-macos", "--", `printf '%s\n' '{"action":"setup-password-focus"}' | /usr/bin/nc -U "$HOME/Library/Caches/dev.cage.GuestClaudeWindow/window.sock"`)...)
214新增: cmd.Env = []string{"PATH=/usr/bin:/bin", "LC_ALL=C"}
215新增: data, err := cmd.Output()
216新增: var result struct {
217新增: Focused bool `json:"focused"`
218新增: }
219新增: return err == nil && json.Unmarshal(data, &result) == nil && result.Focused
220新增:}
221新增:
222新增:func run(ctx context.Context, machine *apple.VirtualMachine, dir string) error {
223新增: if !driver.OwnsOffscreenView(dir) {
224新增: return errors.New("invalid local macOS login view")
225新增: }
226新增: socket := filepath.Join(dir, "cage-login.sock")
227新增: if fi, err := os.Lstat(socket); err == nil {
228新增: if fi.Mode()&os.ModeSocket == 0 {
229新增: return errors.New("unexpected login socket path")
230新增: }
231新增: existing, err := net.DialTimeout("unix", socket, 300*time.Millisecond)
232新增: if err == nil {
233新增: existing.Close()
234新增: return errors.New("this instance already has a login view")
235新增: }
236新增: if err = os.Remove(socket); err != nil {
237新增: return err
238新增: }
239新增: }
240新增: ln, err := net.ListenUnix("unix", &net.UnixAddr{Name: socket, Net: "unix"})
241新增: if err != nil {
242新增: return err
243新增: }
244新增: defer ln.Close()
245新增: if err = os.Chmod(socket, 0600); err != nil {
246新增: return err
247新增: }
248新增: runCtx, cancel := context.WithCancel(ctx)
249新增: defer cancel()
250新增: s := loginSession{profile: filepath.Dir(os.Getenv("CLAUDE_CAGE_CONFIG"))}
251新增: go func() {
252新增: for {
253新增: _ = ln.SetDeadline(time.Now().Add(time.Second))
254新增: conn, err := ln.Accept()
255新增: if err != nil {
256新增: if n, ok := err.(net.Error); ok && n.Timeout() && runCtx.Err() == nil {
257新增: if s.token != "" && (time.Now().After(s.expires) || s.currentScreen() != s.screenID) {
258新增: s.close()
259新增: }
260新增: continue
261新增: }
262新增: return
263新增: }
264新增: _ = conn.SetDeadline(time.Now().Add(10 * time.Second))
265新增: var input request
266新增: if json.NewDecoder(io.LimitReader(conn, 4096)).Decode(&input) == nil {
267新增: _ = json.NewEncoder(conn).Encode(s.handle(input))
268新增: }
269新增: _ = conn.Close()
270新增: }
271新增: }()
272新增: go func() {
273新增: ticker := time.NewTicker(250 * time.Millisecond)
274新增: defer ticker.Stop()
275新增: running := false
276新增: for {
277新增: select {
278新增: case <-runCtx.Done():
279新增: C.cageLoginStop()
280新增: return
281新增: case <-ticker.C:
282新增: state := machine.State()
283新增: if state == apple.VirtualMachineStateRunning {
284新增: running = true
285新增: }
286新增: if running && (state == apple.VirtualMachineStateStopped || state == apple.VirtualMachineStateError) {
287新增: C.cageLoginStop()
288新增: return
289新增: }
290新增: }
291新增: }
292新增: }()
293新增: ref, ok := any(machine).(objectReference)
294新增: if !ok {
295新增: return errors.New("this build has no macOS login view")
296新增: }
297新增: C.cageLoginLoop(ref.CageViewObject())
298新增: runtime.KeepAlive(machine)
299新增: return nil
300新增:}
新增internal/maclogin/screen.go+91 −0看文件
@@ -0,0 +1,91 @@
1新增:package maclogin
2新增:
3新增:import (
4新增: "bytes"
5新增: "encoding/xml"
6新增: "io"
7新增: "os"
8新增: "strconv"
9新增: "strings"
10新增:
11新增: "github.com/google/uuid"
12新增:)
13新增:
14新增:// The trusted guest probe supplies the console owner and bound account UID
15新增:// before Apple's unmodified IOConsoleUsers array. Accept exactly one active,
16新增:// completed, explicitly locked session for that same user.
17新增:func permittedLoginScreen(data []byte, user string) string {
18新增: if bytes.Equal(data, []byte("system-login")) {
19新增: return "system-login"
20新增: }
21新增: header, payload, ok := bytes.Cut(data, []byte("\n"))
22新增: fields := strings.Fields(string(header))
23新增: if !ok || len(fields) != 3 || fields[1] != user || fields[0] != fields[2] {
24新增: return ""
25新增: }
26新增: uid, err := strconv.ParseUint(fields[0], 10, 32)
27新增: if err != nil || uid < 500 || len(payload) > 32<<10 {
28新增: return ""
29新增: }
30新增: type item struct {
31新增: XMLName xml.Name
32新增: Value string `xml:",chardata"`
33新增: }
34新增: var doc struct {
35新增: XMLName xml.Name `xml:"plist"`
36新增: Values []struct {
37新增: XMLName xml.Name
38新增: Records []struct {
39新增: XMLName xml.Name
40新增: Items []item `xml:",any"`
41新增: } `xml:",any"`
42新增: } `xml:",any"`
43新增: }
44新增: decoder := xml.NewDecoder(bytes.NewReader(bytes.TrimSpace(payload)))
45新增: if decoder.Decode(&doc) != nil || len(doc.Values) != 1 || doc.Values[0].XMLName.Local != "array" {
46新增: return ""
47新增: }
48新增: if _, err := decoder.Token(); err != io.EOF {
49新增: return ""
50新增: }
51新增: key := ""
52新增: for _, record := range doc.Values[0].Records {
53新增: if record.XMLName.Local != "dict" || len(record.Items)%2 != 0 {
54新增: return ""
55新增: }
56新增: values := map[string]item{}
57新增: for i := 0; i < len(record.Items); i += 2 {
58新增: k, v := record.Items[i], record.Items[i+1]
59新增: if k.XMLName.Local != "key" || k.Value == "" || values[k.Value].XMLName.Local != "" {
60新增: return ""
61新增: }
62新增: values[k.Value] = v
63新增: }
64新增: on := values["kCGSSessionOnConsoleKey"]
65新增: if on.XMLName.Local == "false" && on.Value == "" {
66新增: continue
67新增: }
68新增: boolTrue := func(k string) bool { v := values[k]; return v.XMLName.Local == "true" && v.Value == "" }
69新增: id, name := values["kCGSSessionUserIDKey"], values["kCGSSessionUserNameKey"]
70新增: session := values["CGSSessionUniqueSessionUUID"]
71新增: sessionID, err := uuid.Parse(session.Value)
72新增: if key != "" || !boolTrue("kCGSSessionOnConsoleKey") || !boolTrue("kCGSessionLoginDoneKey") ||
73新增: !boolTrue("CGSSessionScreenIsLocked") || id.XMLName.Local != "integer" || id.Value != fields[0] ||
74新增: name.XMLName.Local != "string" || name.Value != user || session.XMLName.Local != "string" || err != nil || sessionID == uuid.Nil {
75新增: return ""
76新增: }
77新增: key = "locked-" + sessionID.String()
78新增: }
79新增: return key
80新增:}
81新增:
82新增:// Lima can shorten a Unix socket path with a symlink on macOS. Bind the view
83新增:// to the same existing instance directory, including /tmp and /private/tmp.
84新增:func sameGuestDirectory(actual, expected string) bool {
85新增: a, err := os.Stat(actual)
86新增: if err != nil || !a.IsDir() {
87新增: return false
88新增: }
89新增: b, err := os.Stat(expected)
90新增: return err == nil && b.IsDir() && os.SameFile(a, b)
91新增:}
新增internal/maclogin/screen_test.go+51 −0看文件
@@ -0,0 +1,51 @@
1新增:package maclogin
2新增:
3新增:import (
4新增: "os"
5新增: "path/filepath"
6新增: "strings"
7新增: "testing"
8新增:)
9新增:
10新增:func TestLockedConsoleBoundToOneUserAndSession(t *testing.T) {
11新增: const session = "607bceb6-c53f-4253-bad4-9c22b4ae7325"
12新增: const row = "<dict><key>kCGSSessionOnConsoleKey</key><true/><key>kCGSessionLoginDoneKey</key><true/><key>CGSSessionScreenIsLocked</key><true/><key>kCGSSessionUserIDKey</key><integer>502</integer><key>kCGSSessionUserNameKey</key><string>trial</string><key>CGSSessionUniqueSessionUUID</key><string>" + session + "</string></dict>"
13新增: const other = "<dict><key>kCGSSessionOnConsoleKey</key><false/></dict>"
14新增: makeProbe := func(header, rows string) string { return header + "\n<plist><array>" + rows + "</array></plist>" }
15新增: valid := makeProbe("502 trial 502", row)
16新增: for _, tc := range []struct{ label, input, want string }{
17新增: {"system login", "system-login", "system-login"},
18新增: {"locked", valid, "locked-" + session},
19新增: {"logged-out second user", makeProbe("502 trial 502", other+row), "locked-" + session},
20新增: {"unlocked", strings.Replace(valid, "ScreenIsLocked</key><true/>", "ScreenIsLocked</key><false/>", 1), ""},
21新增: {"missing lock value", strings.Replace(valid, "<key>CGSSessionScreenIsLocked</key><true/>", "", 1), ""},
22新增: {"wrong lock type", strings.Replace(valid, "ScreenIsLocked</key><true/>", "ScreenIsLocked</key><string>true</string>", 1), ""},
23新增: {"different console", makeProbe("503 other 502", row), ""},
24新增: {"different profile UID", makeProbe("503 trial 502", row), ""},
25新增: {"different registry UID", strings.Replace(valid, "<integer>502", "<integer>503", 1), ""},
26新增: {"different registry user", strings.Replace(valid, "<string>trial", "<string>other", 1), ""},
27新增: {"not logged in", strings.Replace(valid, "LoginDoneKey</key><true/>", "LoginDoneKey</key><false/>", 1), ""},
28新增: {"ambiguous", makeProbe("502 trial 502", row+row), ""},
29新增: {"missing session identity", strings.Replace(valid, session, "", 1), ""},
30新增: {"missing active flag", strings.Replace(valid, "<key>kCGSSessionOnConsoleKey</key><true/>", "", 1), ""},
31新增: {"bad plist", valid + "<", ""},
32新增: {"no session", makeProbe("502 trial 502", other), ""},
33新增: } {
34新增: t.Run(tc.label, func(t *testing.T) {
35新增: if got := permittedLoginScreen([]byte(tc.input), "trial"); got != tc.want {
36新增: t.Fatalf("allowed screen %q; want %q", got, tc.want)
37新增: }
38新增: })
39新增: }
40新增:}
41新增:
42新增:func TestOffscreenViewMatchesDirectoryAliases(t *testing.T) {
43新增: instance := t.TempDir()
44新增: alias := filepath.Join(t.TempDir(), "lima-mac")
45新增: if err := os.Symlink(instance, alias); err != nil {
46新增: t.Skipf("symlink unavailable: %v", err)
47新增: }
48新增: if !sameGuestDirectory(alias, instance) || sameGuestDirectory(t.TempDir(), instance) || sameGuestDirectory(filepath.Join(alias, "absent"), filepath.Join(instance, "absent")) {
49新增: t.Fatal("offscreen view must be bound to an existing instance, including its socket path alias")
50新增: }
51新增:}
新增internal/maclogin/typing.go+42 −0看文件
@@ -0,0 +1,42 @@
1新增:package maclogin
2新增:
3新增:type loginKey struct {
4新增: code int
5新增: shift bool
6新增:}
7新增:
8新增:// These are the physical ANSI keys used by the installer's US login layout.
9新增:func passwordKeys(password string) ([]loginKey, bool) {
10新增: rows := []struct {
11新增: characters string
12新增: code int
13新增: }{
14新增: {"aA", 0}, {"sS", 1}, {"dD", 2}, {"fF", 3}, {"hH", 4}, {"gG", 5}, {"zZ", 6}, {"xX", 7}, {"cC", 8}, {"vV", 9},
15新增: {"bB", 11}, {"qQ", 12}, {"wW", 13}, {"eE", 14}, {"rR", 15}, {"yY", 16}, {"tT", 17},
16新增: {"1!", 18}, {"2@", 19}, {"3#", 20}, {"4$", 21}, {"6^", 22}, {"5%", 23}, {"=+", 24}, {"9(", 25}, {"7&", 26}, {"-_", 27}, {"8*", 28}, {"0)", 29},
17新增: {"]}", 30}, {"oO", 31}, {"uU", 32}, {"[{", 33}, {"iI", 34}, {"pP", 35}, {"lL", 37}, {"jJ", 38}, {"'\"", 39}, {"kK", 40}, {";:", 41}, {"\\|", 42}, {",<", 43}, {"/?", 44}, {"nN", 45}, {"mM", 46}, {".>", 47}, {"`~", 50}, {" ", 49},
18新增: }
19新增: if len(password) < 8 || len(password) > 256 {
20新增: return nil, false
21新增: }
22新增: result := make([]loginKey, 0, len(password))
23新增: for _, ch := range password {
24新增: found := false
25新增: for _, row := range rows {
26新增: for index, candidate := range row.characters {
27新增: if ch == candidate {
28新增: result = append(result, loginKey{row.code, index == 1})
29新增: found = true
30新增: break
31新增: }
32新增: }
33新增: if found {
34新增: break
35新增: }
36新增: }
37新增: if !found {
38新增: return nil, false
39新增: }
40新增: }
41新增: return result, true
42新增:}
新增internal/maclogin/typing_test.go+26 −0看文件
@@ -0,0 +1,26 @@
1新增:package maclogin
2新增:
3新增:import "testing"
4新增:
5新增:func TestPasswordKeysKeepPrintableKeysSeparateFromSubmit(t *testing.T) {
6新增: keys, ok := passwordKeys("Aa7! _-\\\"[]{}")
7新增: if !ok || len(keys) != 13 {
8新增: t.Fatalf("password encoding failed: %v %d", ok, len(keys))
9新增: }
10新增: if keys[0] != (loginKey{0, true}) || keys[1] != (loginKey{0, false}) || keys[3] != (loginKey{18, true}) {
11新增: t.Fatal("shifted keys lost their physical code")
12新增: }
13新增: for _, key := range keys {
14新增: if key.code == 36 || key.code == 48 || key.code == 53 {
15新增: t.Fatal("password emitted a submit or navigation key")
16新增: }
17新增: }
18新增: for _, value := range []string{"password\nreturn", "password\x00", "密码password"} {
19新增: if _, ok := passwordKeys(value); ok {
20新增: t.Fatal("accepted control or unsupported character")
21新增: }
22新增: }
23新增: if _, ok := passwordKeys("short"); ok {
24新增: t.Fatal("accepted invalid length")
25新增: }
26新增:}
新增internal/vm/host_source_test.go+52 −0看文件
@@ -0,0 +1,52 @@
1新增:package vm
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "io"
6新增: "os"
7新增: "path/filepath"
8新增: "strings"
9新增: "testing"
10新增:
11新增: "github.com/sylvinus/agent-vm/internal/cage"
12新增: "github.com/sylvinus/agent-vm/internal/hostimage"
13新增:)
14新增:
15新增:func TestHostLinuxImageHasNoFallbackOrHostMounts(t *testing.T) {
16新增: l := newTestLima(t)
17新增: directory := t.TempDir()
18新增: config := filepath.Join(directory, "config.json")
19新增: data, _ := json.Marshal(cage.DefaultConfig())
20新增: if err := os.WriteFile(config, data, 0600); err != nil {
21新增: t.Fatal(err)
22新增: }
23新增: t.Setenv(cage.ConfigEnv, config)
24新增: plan := hostimage.Plan{Host: hostimage.Identity{System: "ubuntu-22.04", Version: "22.04", Arch: "amd64"}, Version: "22.04", Format: "qcow2", Path: filepath.Join(directory, "ubuntu.img"), Digest: "sha256:" + strings.Repeat("a", 64)}
25新增: if err := hostimage.WriteLinuxTemplate(directory, plan); err != nil {
26新增: t.Fatal(err)
27新增: }
28新增: template, err := hostimage.LinuxTemplate(directory)
29新增: if err != nil {
30新增: t.Fatal(err)
31新增: }
32新增: none := []Mount{}
33新增: if err := l.Create(t.Context(), "x", template, Settings{Mounts: &none, NoContainerd: true}, io.Discard); err != nil {
34新增: t.Fatal(err)
35新增: }
36新增: instance, err := l.inspect(t.Context(), "x")
37新增: if err != nil {
38新增: t.Fatal(err)
39新增: }
40新增: if len(instance.Config.Images) != 1 || instance.Config.Images[0].Location != plan.Path || string(instance.Config.Images[0].Digest) != plan.Digest {
41新增: t.Fatalf("unexpected image fallback: %+v", instance.Config.Images)
42新增: }
43新增: if len(instance.Config.Mounts) != 0 {
44新增: t.Fatal("host directories were mounted")
45新增: }
46新增: if err := hostimage.ClearLinuxTemplate(directory, plan); err != nil {
47新增: t.Fatal(err)
48新增: }
49新增: if path, err := hostimage.LinuxTemplate(directory); err != nil || path != "template:debian-13" {
50新增: t.Fatalf("selection was retained: %q %v", path, err)
51新增: }
52新增:}
修改internal/vm/lima.go+38 −5看文件
@@ -16,6 +16,7 @@ import (
1616 "strconv"
1717 "strings"
1818 "sync"
19新增: "time"
1920
2021 "al.essio.dev/pkg/shellescape"
2122 "github.com/coreos/go-semver/semver"
@@ -326,10 +327,15 @@ func (l *Lima) Create(ctx context.Context, name, template string, s Settings, lo
326327 e = append(e, ".images = "+string(images))
327328 // cloud-init rewrites Debian's mirror list after bootcmd.
328329 // Configure it immediately before Lima installs dependencies.
329删除: e = append(e, `.provision += [{"mode": "dependency", "script": `+strconv.Quote(cage.DebianMirrorsScript)+`}]`)
330新增: e = append(e, `.provision += [{"mode": "dependency", "script": `+strconv.Quote(cage.DebianPrepareScript)+`}]`)
330331 }
331332 tz, _ := json.Marshal(cfg.Timezone)
332删除: e = append(e, ".propagateProxyEnv = false", `.env = {"http_proxy":"","https_proxy":"","ftp_proxy":"","no_proxy":"","HTTP_PROXY":"","HTTPS_PROXY":"","FTP_PROXY":"","NO_PROXY":"","ALL_PROXY":"","all_proxy":""}`, ".timezone = "+string(tz), ".user.name = \"cage\"", ".user.home = \"/home/cage\"", ".user.uid = 1000")
333新增: e = append(e, ".propagateProxyEnv = false", `.env = {"http_proxy":"","https_proxy":"","ftp_proxy":"","no_proxy":"","HTTP_PROXY":"","HTTPS_PROXY":"","FTP_PROXY":"","NO_PROXY":"","ALL_PROXY":"","all_proxy":""}`, ".timezone = "+string(tz))
334新增: if tmpl.Config.OS != nil && *tmpl.Config.OS == limatype.DARWIN {
335新增: e = append(e, `.user.name = "cageprovision"`, `.user.home = "/Users/cageprovision"`, `.user.comment = "Cage Provisioning"`, ".user.uid = 501", `.video.display = "offscreen"`)
336新增: } else {
337新增: e = append(e, `.user.name = "cage"`, `.user.home = "/home/cage"`, ".user.uid = 1000")
338新增: }
333339 }
334340 if len(e) > 0 {
335341 if tmpl.Bytes, err = yqutil.EvaluateExpression(ctx, yqutil.Join(e), tmpl.Bytes); err != nil {
@@ -515,8 +521,25 @@ func (l *Lima) Start(ctx context.Context, name string, log io.Writer) error {
515521 // Here, so that VMs made before it get it too; nothing is written when
516522 // it is there already.
517523 settings := Settings{noEphemeralPorts: true}
518删除: if os.Getenv(cage.ConfigEnv) != "" {
519删除: settings.MemoryGiB, settings.CPUs = cage.ResourceLimits()
524新增: if configPath := os.Getenv(cage.ConfigEnv); configPath != "" {
525新增: allocation, loadErr := cage.LoadResourceAllocation(configPath)
526新增: if loadErr != nil {
527新增: return loadErr
528新增: }
529新增: settings.MemoryGiB, settings.CPUs, err = allocation.Limits()
530新增: if *inst.Config.OS == limatype.DARWIN && err == nil {
531新增: requirements, requirementErr := ReadMacOSResourceRequirements(inst.Dir)
532新增: if requirementErr != nil {
533新增: return requirementErr
534新增: }
535新增: settings.MemoryGiB, settings.CPUs, err = requirements.Limits(allocation)
536新增: if err == nil {
537新增: err = saveMacOSResourceRequirements(inst.Dir, requirements)
538新增: }
539新增: }
540新增: if err != nil {
541新增: return err
542新增: }
520543 }
521544 if err := l.Edit(ctx, name, settings); err != nil {
522545 return err
@@ -530,11 +553,21 @@ func (l *Lima) Start(ctx context.Context, name string, log io.Writer) error {
530553 if err := NetworkConfined(inst.Config); err != nil {
531554 return err
532555 }
556新增: var guestAgent string
557新增: // Lima always needs the Darwin helper for first boot. Windows and FreeBSD
558新增: // have no guest agent, and Linux plain mode works without one.
559新增: if *inst.Config.OS == limatype.DARWIN || (*inst.Config.OS == limatype.LINUX && !*inst.Config.Plain) {
560新增: guestAgent, err = share.GuestAgent(*inst.Config.OS, *inst.Config.Arch)
561新增: if err != nil {
562新增: return err
563新增: }
564新增: }
533565 return withLog(log, func() error {
534566 if err := reconcile.Reconcile(ctx, name); err != nil {
535567 return err
536568 }
537删除: return instance.StartWithPaths(ctx, inst, false, false, "", share.GuestAgent)
569新增: started := time.Now()
570新增: return vmStartError(instance.StartWithPaths(ctx, inst, false, false, "", guestAgent), inst.Dir, started)
538571 })
539572}
540573
修改internal/vm/lima_test.go+45 −1看文件
@@ -16,12 +16,14 @@ import (
1616 "testing"
1717 "time"
1818
19新增: "github.com/lima-vm/lima/v2/pkg/driverutil"
1920 "github.com/lima-vm/lima/v2/pkg/guestagent/api"
2021 "github.com/lima-vm/lima/v2/pkg/hostagent/events"
2122 "github.com/lima-vm/lima/v2/pkg/limatype"
2223 "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
2324 "github.com/lima-vm/lima/v2/pkg/limayaml"
2425 "github.com/lima-vm/lima/v2/pkg/portfwd"
26新增: "github.com/lima-vm/lima/v2/pkg/registry"
2527
2628 "github.com/sylvinus/agent-vm/internal/cage"
2729 "github.com/sylvinus/agent-vm/internal/limaembed"
@@ -67,7 +69,7 @@ func TestCageDebianMirrors(t *testing.T) {
6769 }
6870 earlyAPT := false
6971 for _, step := range instance.Config.Provision {
70删除: if step.Mode == limatype.ProvisionModeDependency && step.Script != nil && *step.Script == cage.DebianMirrorsScript {
72新增: if step.Mode == limatype.ProvisionModeDependency && step.Script != nil && *step.Script == cage.DebianPrepareScript {
7173 earlyAPT = true
7274 }
7375 }
@@ -489,6 +491,48 @@ func TestUserLimaHome(t *testing.T) {
489491 }
490492}
491493
494新增:func TestLimaDrivers(t *testing.T) {
495新增: l := newTestLima(t)
496新增: ctx := t.Context()
497新增: none := []Mount{}
498新增: if err := l.Create(ctx, "base", "template:debian-13", Settings{Mounts: &none}, io.Discard); err != nil {
499新增: t.Fatal(err)
500新增: }
501新增: for _, kind := range []string{limatype.QEMU, limatype.VZ} {
502新增: if registry.CheckInternalOrExternal(kind) != registry.Internal {
503新增: continue
504新增: }
505新增: t.Run(kind, func(t *testing.T) {
506新增: first, err := l.inspect(ctx, "base")
507新增: if err != nil {
508新增: t.Fatal(err)
509新增: }
510新增: second, err := l.inspect(ctx, "base")
511新增: if err != nil {
512新增: t.Fatal(err)
513新增: }
514新增: first.Dir = filepath.Join(first.Dir, "first")
515新增: second.Dir = filepath.Join(second.Dir, "second")
516新增: first.Config.VMType = &kind
517新增: second.Config.VMType = &kind
518新增: firstDriver, err := driverutil.CreateConfiguredDriver(ctx, first, 0)
519新增: if err != nil {
520新增: t.Fatal(err)
521新增: }
522新增: secondDriver, err := driverutil.CreateConfiguredDriver(ctx, second, 0)
523新增: if err != nil {
524新增: t.Fatal(err)
525新增: }
526新增: if firstDriver.Driver == secondDriver.Driver || firstDriver.Info(ctx).InstanceDir != first.Dir {
527新增: t.Fatal("configuring another VM changed the first VM's driver")
528新增: }
529新增: if secondDriver.Info(ctx).InstanceDir != second.Dir {
530新增: t.Fatal("the second driver lost its instance")
531新增: }
532新增: })
533新增: }
534新增:}
535新增:
492536// Edits at once each write a whole lima.yaml, and leave nothing behind.
493537func TestLimaEditConcurrent(t *testing.T) {
494538 ctx := context.Background()
新增internal/vm/macos_guest_e2e_test.go+340 −0看文件
@@ -0,0 +1,340 @@
1新增://go:build darwin && arm64 && cgo && e2e && !no_vz
2新增:
3新增:package vm
4新增:
5新增:import (
6新增: "bytes"
7新增: "context"
8新增: "encoding/json"
9新增: "github.com/google/uuid"
10新增: "image/png"
11新增: "io"
12新增: "os"
13新增: "os/exec"
14新增: "path/filepath"
15新增: "strings"
16新增: "testing"
17新增: "time"
18新增:
19新增: "al.essio.dev/pkg/shellescape"
20新增: "github.com/sylvinus/agent-vm/internal/cage"
21新增: "github.com/sylvinus/agent-vm/internal/guestos"
22新增: "github.com/sylvinus/agent-vm/internal/managedproxy"
23新增:)
24新增:
25新增:// Run the signed test binary with CAGE_TEST_MACOS_IPSW pointing to an Apple
26新增:// restore image. CAGE_TEST_CLAUDE_DMG optionally exercises the official app.
27新增:func TestMacOSGuest(t *testing.T) {
28新增: image := os.Getenv("CAGE_TEST_MACOS_IPSW")
29新增: if image == "" {
30新增: t.Skip("set CAGE_TEST_MACOS_IPSW to a local Apple restore image")
31新增: }
32新增: if !filepath.IsAbs(image) {
33新增: t.Fatal("CAGE_TEST_MACOS_IPSW must be absolute")
34新增: }
35新增: if info, err := os.Stat(image); err != nil || !info.Mode().IsRegular() {
36新增: t.Fatalf("invalid restore image %q: %v", image, err)
37新增: }
38新增: ctx, cancel := context.WithTimeout(context.Background(), 45*time.Minute)
39新增: defer cancel()
40新增: profile, err := os.MkdirTemp("/tmp", "cgmac-")
41新增: if err != nil {
42新增: t.Fatal(err)
43新增: }
44新增: t.Cleanup(func() {
45新增: if t.Failed() && os.Getenv("CAGE_TEST_KEEP_FAILED_VM") == "1" {
46新增: t.Log("Retained this test's private VM for diagnosis:", profile)
47新增: return
48新增: }
49新增: if err := os.RemoveAll(profile); err != nil {
50新增: t.Error(err)
51新增: }
52新增: })
53新增: configPath := filepath.Join(profile, "config.json")
54新增: state := filepath.Join(profile, "state")
55新增: t.Setenv(cage.ConfigEnv, configPath)
56新增: t.Setenv("AGENT_VM_STATE_DIR", state)
57新增: t.Setenv("LIMA_HOME", filepath.Join(state, "lima"))
58新增: t.Setenv("LIMA_CACHE_HOME", filepath.Join(profile, "cache"))
59新增: t.Setenv("AGENT_VM_UNSAFE_OPEN_NETWORK", "")
60新增: t.Setenv("AGENT_VM_UNSAFE_WRITABLE_GIT", "")
61新增: t.Setenv("AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS", "")
62新增: // Use a private, unstarted proxy configuration. Installation uses local
63新增: // media and SSH. No part of this test requires external guest traffic.
64新增: proxy, err := managedproxy.Load(profile)
65新增: if err != nil {
66新增: t.Fatal(err)
67新增: }
68新增: if err := proxy.Import("offline", "", []byte("proxies: [{name: offline, type: socks5, server: 127.0.0.1, port: 9}]"), "offline", 0, ""); err != nil {
69新增: t.Fatal(err)
70新增: }
71新增: proxy.Selected = proxy.Sources[0].Nodes[0].ID
72新增: proxy.Revision = "offline"
73新增: if err := proxy.Save(profile); err != nil {
74新增: t.Fatal(err)
75新增: }
76新增: cfg := cage.DefaultConfig()
77新增: cfg.ProxyURL, cfg.ProxyRevision = proxy.Endpoint(), proxy.Revision
78新增: writeJSON := func(path string, value any) {
79新增: t.Helper()
80新增: data, err := json.Marshal(value)
81新增: if err != nil {
82新增: t.Fatal(err)
83新增: }
84新增: if err := os.WriteFile(path, data, 0600); err != nil {
85新增: t.Fatal(err)
86新增: }
87新增: }
88新增: writeJSON(configPath, cfg)
89新增: writeJSON(cage.ResourceAllocationPath(configPath), cage.ResourceAllocation{MemoryGiB: 4, CPUs: 2})
90新增: l, err := NewLima(filepath.Join(state, "lima"), state)
91新增: if err != nil {
92新增: t.Fatal(err)
93新增: }
94新增: const name = "mac"
95新增: if err := l.CreateMacOSFromIPSW(ctx, name, image, Settings{CPUs: 2, MemoryGiB: 4, DiskGiB: 64}, os.Stderr); err != nil {
96新增: t.Fatal(err)
97新增: }
98新增: t.Cleanup(func() {
99新增: cleanup, cancel := context.WithTimeout(context.Background(), time.Minute)
100新增: defer cancel()
101新增: if err := l.Stop(cleanup, name); err != nil {
102新增: t.Error(err)
103新增: }
104新增: })
105新增: t.Log("Restoring a new macOS test VM from local media")
106新增: if err := l.Start(ctx, name, os.Stderr); err != nil {
107新增: t.Fatal(err)
108新增: }
109新增: run := func(script string, input io.Reader) string {
110新增: t.Helper()
111新增: var out bytes.Buffer
112新增: code, err := l.Shell(ctx, name, ShellOpts{Args: []string{"/bin/sh", "-ec", script}, Stdin: input, Stdout: &out, Stderr: &out})
113新增: if err != nil || code != 0 {
114新增: t.Fatalf("guest command failed (%d): %v\n%s", code, err, out.String())
115新增: }
116新增: return strings.TrimSpace(out.String())
117新增: }
118新增: t.Log(run("test \"$(uname -s)\" = Darwin && /usr/bin/sw_vers && test \"$HOME\" = /Users/cageprovision", nil))
119新增: run("cd \"$HOME\" && /usr/bin/osacompile -l JavaScript -o cage-qa.scpt -e '6*7' && test \"$(/usr/bin/osascript cage-qa.scpt)\" = 42", nil)
120新增: serialKey, err := guestos.MacOSInstallHostKey(profile)
121新增: if err != nil {
122新增: t.Fatal(err)
123新增: }
124新增: guestKey := run("cat /etc/ssh/ssh_host_ed25519_key.pub", nil)
125新增: if !strings.HasPrefix(guestKey+" ", strings.TrimSpace(string(serialKey))+" ") {
126新增: t.Fatal("VZ serial key differs from the restored guest identity")
127新增: }
128新增: if kit := os.Getenv("CAGE_TEST_MACOS_AUTOMATION_KIT"); kit != "" {
129新增: // Minimal first-run experiment: the production account receipt and session
130新增: // configuration run in a newly restored VM, with no daily guest data.
131新增: tar := exec.CommandContext(ctx, "/usr/bin/tar", "--no-mac-metadata", "-cf", "-", "-C", kit, ".")
132新增: pipe, err := tar.StdoutPipe()
133新增: if err != nil {
134新增: t.Fatal(err)
135新增: }
136新增: if err := tar.Start(); err != nil {
137新增: t.Fatal(err)
138新增: }
139新增: run(`mkdir "$HOME/automation-kit"; cd "$HOME/automation-kit"; tar -xf -`, pipe)
140新增: if err := tar.Wait(); err != nil {
141新增: t.Fatal(err)
142新增: }
143新增: password := "Aa7!" + uuid.NewString()
144新增: run(`umask 077; cat > "$HOME/automation-input"`, strings.NewReader(password+"\n"))
145新增: admin := func(script string) string {
146新增: return run("sudo -S -p '' /bin/bash -ec "+shellescape.Quote(script)+` < "$HOME/password"`, nil)
147新增: }
148新增: installation := uuid.NewString()
149新增: admin(`echo macos > /var/db/cage-guest-os; chmod 600 /var/db/cage-guest-os; chown -R root:wheel /Users/cageprovision/automation-kit;
150新增:printf '%s\n' "$(cat /Users/cageprovision/automation-input)" | sysadminctl -addUser cage -fullName cage -password - -home /Users/cage;
151新增:createhomedir -c -u cage >/dev/null;
152新增:/Users/cageprovision/automation-kit/cage-finish-initial-setup prepare ` + installation + ` < /Users/cageprovision/automation-input;
153新增:/bin/bash /Users/cageprovision/automation-kit/configure-macos-session.sh cage ` + installation + ` < /Users/cageprovision/automation-input`)
154新增: run(`test "$(sudo -S -p '' defaults read /Library/Preferences/com.apple.loginwindow autoLoginUser < "$HOME/password")" = cage`, nil)
155新增: if err := l.Stop(ctx, name); err != nil {
156新增: t.Fatal(err)
157新增: }
158新增: if err := l.Start(ctx, name, os.Stderr); err != nil {
159新增: t.Fatal(err)
160新增: }
161新增: loggedIn := false
162新增: for i := 0; i < 60; i++ {
163新增: if run(`stat -f '%Su' /dev/console`, nil) == "cage" {
164新增: loggedIn = true
165新增: break
166新增: }
167新增: time.Sleep(time.Second)
168新增: }
169新增: if !loggedIn {
170新增: t.Fatal("guest did not automatically log in")
171新增: }
172新增: admin(`! pgrep -x 'Setup Assistant' >/dev/null; uid=$(id -u cage); launchctl print gui/$uid >/dev/null;
173新增:/Users/cageprovision/automation-kit/cage-finish-initial-setup;
174新增:! id -Gn cage | grep -qw admin; ! id -Gn cagesetup | grep -qw admin;
175新增:test "$(stat -f %OLp /etc/kcpassword)" = 600`)
176新增: t.Log("Fresh guest: automatic graphical login, skipped optional Setup Assistant, standard account and retired temporary administrator verified")
177新增: return
178新增: }
179新增: if kit, media := os.Getenv("CAGE_TEST_MACOS_WORKBENCH_KIT"), os.Getenv("CAGE_TEST_MACOS_WORKBENCH_MEDIA"); kit != "" && media != "" {
180新增: // Exercise the shipped provisioning script in this disposable fresh VM.
181新增: tar := exec.CommandContext(ctx, "/usr/bin/tar", "--no-mac-metadata", "-cf", "-", "-C", kit, ".", "-C", media, "node.tgz", "editor.tgz", "playwright.tgz", "chrome.dmg", "claude.dmg", "cli", "macfuse.pkg")
182新增: pipe, err := tar.StdoutPipe()
183新增: if err != nil {
184新增: t.Fatal(err)
185新增: }
186新增: tar.Stderr = os.Stderr
187新增: if err := tar.Start(); err != nil {
188新增: t.Fatal(err)
189新增: }
190新增: run(`mkdir "$HOME/kit"; cd "$HOME/kit"; tar -xf -; mv macfuse.pkg project/macfuse.pkg`, pipe)
191新增: if err := tar.Wait(); err != nil {
192新增: t.Fatal(err)
193新增: }
194新增: password := "Aa7!" + uuid.NewString()
195新增: run(`umask 077; cat > "$HOME/login-input"`, strings.NewReader(password+"\n"))
196新增: admin := func(script string) string {
197新增: return run("sudo -S -p '' /bin/bash -ec "+shellescape.Quote(script)+` < "$HOME/password"`, nil)
198新增: }
199新增: stage := admin(`mktemp -d /private/var/tmp/cage-install.XXXXXXXX`)
200新增: admin(`mv /Users/cageprovision/kit ` + stage + `/kit; chown -R root:wheel ` + stage + `; cd /; /bin/bash ` + stage + `/kit/provision-macos-workbench.sh ` + stage + `/kit ` + uuid.NewString() + ` cageprovision < /Users/cageprovision/login-input`)
201新增: run(`/usr/bin/dscl /Local/Default -authonly cage >/dev/null`, strings.NewReader(password+"\n"))
202新增: admin(`test "$(dscl . -read /Users/cage NFSHomeDirectory)" = 'NFSHomeDirectory: /Users/cage'; if id -Gn cage | grep -qw admin; then exit 1; fi; dscl . -read /Users/cageprovision IsHidden | grep -q ": 1$"; /usr/local/libexec/cage-finish-initial-setup`)
203新增: admin(`if id -Gn cagesetup | grep -qw admin; then exit 1; fi; dscl . -read /Users/cagesetup UserShell | grep -q /usr/bin/false`)
204新增: t.Log("Fresh cage account, user-selected password, ordinary privileges and temporary administrator retirement verified")
205新增: }
206新增: verifyMacOSGuestNetwork(t, ctx, filepath.Join(state, "lima", name), run)
207新增: verifyMacOSProjectTransfer(t, ctx, l, name)
208新增: if err := l.Stop(ctx, name); err != nil {
209新增: t.Fatal(err)
210新增: }
211新增: if err := l.Start(ctx, name, os.Stderr); err != nil {
212新增: t.Fatal(err)
213新增: }
214新增: run("test \"$(/usr/bin/osascript \"$HOME/cage-qa.scpt\")\" = 42", nil)
215新增: t.Log("Native compilation, closed external connection and persistent disk verified")
216新增: if dmg := os.Getenv("CAGE_TEST_CLAUDE_DMG"); dmg != "" {
217新增: h, err := os.ReadFile("../../scripts/guest-os/claude-desktop-macos.sh")
218新增: if err != nil {
219新增: t.Fatal(err)
220新增: }
221新增: run("umask 077; cat > \"$HOME/claude-desktop-qa.sh\"", bytes.NewReader(h))
222新增: f, err := os.Open(dmg)
223新增: if err != nil {
224新增: t.Fatal(err)
225新增: }
226新增: defer f.Close()
227新增: run("umask 077; cat > \"$HOME/Claude.dmg\"", f)
228新增: // Lima generates a random password inside this new VM. Use it only
229新增: // for this guest's privileged setup, without transferring it to the host.
230新增: admin := func(script string) string {
231新增: t.Helper()
232新增: return run("sudo -S -p '' -- /bin/sh -ec "+shellescape.Quote(script)+` < "$HOME/password"`, nil)
233新增: }
234新增: admin("umask 022; echo macos > /var/db/cage-guest-os")
235新增: t.Log(admin("/bin/bash /Users/cageprovision/claude-desktop-qa.sh install /Users/cageprovision/Claude.dmg"))
236新增: t.Log(run("/bin/bash \"$HOME/claude-desktop-qa.sh\" inspect", nil))
237新增: if helper := os.Getenv("CAGE_TEST_CLAUDE_WINDOW"); helper != "" {
238新增: t.Log(run("/bin/bash \"$HOME/claude-desktop-qa.sh\" launch", nil))
239新增: f, err := os.Open(helper)
240新增: if err != nil {
241新增: t.Fatal(err)
242新增: }
243新增: defer f.Close()
244新增: run(`umask 077; cat > "$HOME/window-helper"`, f)
245新增: admin("mkdir -p /usr/local/libexec && install -o root -g wheel -m 755 /Users/cageprovision/window-helper /usr/local/libexec/cage-claude-window")
246新增: var frame, stderr bytes.Buffer
247新增: code, err := l.Shell(ctx, name, ShellOpts{
248新增: Args: []string{"/bin/sh", "-ec", `sudo -S -p '' /bin/launchctl asuser "$(id -u)" sudo -nu "$(id -un)" -- /usr/local/libexec/cage-claude-window < "$HOME/password"`},
249新增: Stdout: &frame, Stderr: &stderr,
250新增: })
251新增: if err != nil || code != 0 {
252新增: t.Fatalf("single-window capture (%d): %v %s", code, err, stderr.String())
253新增: }
254新增: img, err := png.DecodeConfig(&frame)
255新增: if err != nil || img.Width <= 0 || img.Height <= 0 {
256新增: t.Fatalf("invalid window PNG: %v", err)
257新增: }
258新增: t.Logf("Verified Claude window PNG, %d × %d", img.Width, img.Height)
259新增: }
260新增: }
261新增:}
262新增:
263新增:// A failed request alone could mean that the guest network is misconfigured.
264新增:// Check that each guest probe reached the closed gate for this instance.
265新增:func verifyMacOSGuestNetwork(t *testing.T, ctx context.Context, instance string, run func(string, io.Reader) string) {
266新增: t.Helper()
267新增: client, err := cage.OpenGateClient(instance)
268新增: if err != nil {
269新增: t.Fatal(err)
270新增: }
271新增: status := func() cage.GateStatus {
272新增: t.Helper()
273新增: s, err := client.Status(ctx)
274新增: if err != nil {
275新增: t.Fatal(err)
276新增: }
277新增: if s.Mode != cage.GateClosed {
278新增: t.Fatalf("expected a closed network gate, got %q", s.Mode)
279新增: }
280新增: return s
281新增: }
282新增: check := func(label, script string, denied func(cage.GateCounters) uint64) {
283新增: t.Helper()
284新增: before := status()
285新增: run(script, nil)
286新增: deadline := time.Now().Add(3 * time.Second)
287新增: for {
288新增: after := status()
289新增: if after.RunID != before.RunID || after.Epoch != before.Epoch {
290新增: t.Fatalf("network gate changed during %s probe", label)
291新增: }
292新增: if n := denied(after.Counters); n > denied(before.Counters) {
293新增: t.Logf("Closed gate denied guest %s (%d → %d)", label, denied(before.Counters), n)
294新增: return
295新增: }
296新增: if time.Now().After(deadline) {
297新增: t.Fatalf("host gate did not record the guest %s probe", label)
298新增: }
299新增: time.Sleep(100 * time.Millisecond)
300新增: }
301新增: }
302新增: check("TCP", "if /usr/bin/nc -G 2 -z 1.1.1.1 443; then exit 1; fi", func(c cage.GateCounters) uint64 { return c.TCPDenied })
303新增: // Sending a UDP datagram can succeed locally even when the host drops it.
304新增: check("UDP", "printf cage | /usr/bin/nc -u -w 1 1.1.1.1 3478", func(c cage.GateCounters) uint64 { return c.UDPDenied })
305新增: check("DNS", `resolver=$(awk '/^nameserver[[:space:]]/{print $2; exit}' /etc/resolv.conf)
306新增:test -n "$resolver"
307新增:response=$(/usr/bin/dig @"$resolver" +time=2 +tries=1 +noall +comments +answer "cage-check-$(uuidgen).example.com." A) || :
308新增:if printf '%s\n' "$response" | grep -Eq 'status: NOERROR|[[:space:]]IN[[:space:]]+A[[:space:]]'; then exit 1; fi`, func(c cage.GateCounters) uint64 { return c.DNSDenied })
309新增:
310新增: if _, err := client.BeginCheck(ctx); err != nil {
311新增: t.Fatal(err)
312新增: }
313新增: defer func() {
314新增: if _, err := client.Close(ctx, "guest network test finished"); err != nil {
315新增: t.Error(err)
316新增: }
317新增: }()
318新增: probe := func(path, want string) {
319新增: t.Helper()
320新增: response := run("curl --noproxy '*' -sS --max-time 15 -o /dev/null -w '%{http_code}' http://"+cage.DiagnosticHost+path, nil)
321新增: if response != want {
322新增: t.Fatalf("guest diagnostic %s: got %q, want %q", path, response, want)
323新增: }
324新增: }
325新增: probe("/", "200")
326新增: before, err := client.SetFault(ctx, true)
327新增: if err != nil {
328新增: t.Fatal(err)
329新增: }
330新增: probe("/egress", "503")
331新增: probe("/dns", "503")
332新增: after, err := client.Status(ctx)
333新增: if err != nil {
334新增: t.Fatal(err)
335新增: }
336新增: if after.Counters.FaultTCP <= before.Counters.FaultTCP || after.Counters.FaultDNS <= before.Counters.FaultDNS {
337新增: t.Fatal("missing proxy fault observations for guest TCP or DNS")
338新增: }
339新增: t.Log("Guest diagnostic service reachable; both fixed probes reported injected proxy failure")
340新增:}
新增internal/vm/macos_install_darwin_arm64.go+222 −0看文件
@@ -0,0 +1,222 @@
1新增://go:build darwin && arm64 && cgo && !no_vz
2新增:
3新增:package vm
4新增:
5新增:import (
6新增: "context"
7新增: "encoding/json"
8新增: "errors"
9新增: "fmt"
10新增: "io"
11新增: "os"
12新增: "path/filepath"
13新增: "strings"
14新增:
15新增: "github.com/Code-Hex/vz/v3"
16新增: "github.com/lima-vm/lima/v2/pkg/fileutils"
17新增: "github.com/lima-vm/lima/v2/pkg/limatype"
18新增: "github.com/lima-vm/lima/v2/pkg/limatype/dirnames"
19新增:)
20新增:
21新增:// CheckMacOSGuest verifies a prepared instance before binding or starting a
22新增:// native workbench. Project access goes through a separate confined service.
23新增:func (l *Lima) CheckMacOSGuest(ctx context.Context, name string) error {
24新增: inst, err := l.inspect(ctx, name)
25新增: if err != nil {
26新增: return err
27新增: }
28新增: c := inst.Config
29新增: if c == nil || c.OS == nil || *c.OS != limatype.DARWIN || c.VMType == nil || *c.VMType != limatype.VZ ||
30新增: len(c.Mounts) != 0 || len(c.AdditionalDisks) != 0 || c.Video.Display == nil || *c.Video.Display != "offscreen" {
31新增: return errors.New("expected a headless macOS VZ guest with its own system disk and no host shares")
32新增: }
33新增: for _, p := range c.PortForwards {
34新增: if !p.Ignore {
35新增: return errors.New("macOS guest has an unmanaged forwarded port")
36新增: }
37新增: }
38新增: return NetworkConfined(c)
39新增:}
40新增:
41新增:// MatchMacOSInstallSource permits retrying an interrupted restore only with
42新增:// the same pinned IPSW. An existing disk is left to Lima's restore transaction.
43新增:func (l *Lima) MatchMacOSInstallSource(ctx context.Context, name, image string) error {
44新增: if err := l.CheckMacOSGuest(ctx, name); err != nil {
45新增: return err
46新增: }
47新增: inst, err := l.inspect(ctx, name)
48新增: if err != nil {
49新增: return err
50新增: }
51新增: if !filepath.IsAbs(image) || len(inst.Config.Images) != 1 {
52新增: return errors.New("an interrupted installation requires its original local IPSW")
53新增: }
54新增: image, err = filepath.EvalSymlinks(image)
55新增: if err != nil {
56新增: return err
57新增: }
58新增: original := inst.Config.Images[0]
59新增: if original.Location != image || original.Digest == "" {
60新增: return errors.New("the existing macOS installation uses different restore media")
61新增: }
62新增: info, err := os.Stat(image)
63新增: if err != nil {
64新增: return err
65新增: }
66新增: if !info.Mode().IsRegular() {
67新增: return errors.New("the restore image must be a regular file")
68新增: }
69新增: digest, err := fileutils.RestoreImageDigest(ctx, image, info)
70新增: if err != nil {
71新增: return err
72新增: }
73新增: if string(original.Digest) != string(digest) {
74新增: return errors.New("the existing macOS installation is pinned to a different IPSW digest")
75新增: }
76新增: return nil
77新增:}
78新增:
79新增:// CreateMacOSFromIPSW creates the stopped VM. Lima restores the local image
80新增:// into its private disk at first start, so the source must remain available.
81新增:func (l *Lima) CreateMacOSFromIPSW(ctx context.Context, name, imagePath string, settings Settings, log io.Writer) error {
82新增: if err := ctx.Err(); err != nil {
83新增: return err
84新增: }
85新增: if settings.Mounts != nil && len(*settings.Mounts) != 0 {
86新增: return errors.New("macOS installation does not accept shared host directories")
87新增: }
88新增: if err := dirnames.ValidateInstName(name); err != nil {
89新增: return err
90新增: }
91新增: if !filepath.IsAbs(imagePath) || !strings.EqualFold(filepath.Ext(imagePath), ".ipsw") {
92新增: return errors.New("select a local .ipsw file using its absolute path")
93新增: }
94新增: image, err := filepath.EvalSymlinks(imagePath)
95新增: if err != nil {
96新增: return err
97新增: }
98新增: info, err := os.Stat(image)
99新增: if err != nil {
100新增: return err
101新增: }
102新增: if !info.Mode().IsRegular() {
103新增: return errors.New("the selected IPSW must be a regular file")
104新增: }
105新增: home, err := dirnames.LimaDir()
106新增: if err != nil {
107新增: return err
108新增: }
109新增: // Compare actual directories, including on case-insensitive volumes and a
110新增: // profile whose Lima home is a symlink to another volume.
111新增: store, err := os.Stat(home)
112新增: if err != nil && !errors.Is(err, os.ErrNotExist) {
113新增: return err
114新增: }
115新增: if store != nil {
116新增: for dir := filepath.Dir(image); ; dir = filepath.Dir(dir) {
117新增: ancestor, err := os.Stat(dir)
118新增: if err != nil {
119新增: return err
120新增: }
121新增: if os.SameFile(ancestor, store) {
122新增: return errors.New("keep the source IPSW outside the Lima instance storage directory")
123新增: }
124新增: if filepath.Dir(dir) == dir {
125新增: break
126新增: }
127新增: }
128新增: }
129新增: restore, err := vz.LoadMacOSRestoreImageFromPath(image)
130新增: if err != nil {
131新增: return fmt.Errorf("Apple Virtualization could not read the selected restore image: %w", err)
132新增: }
133新增: if err := applyMacOSRequirements(restore, &settings); err != nil {
134新增: return err
135新增: }
136新增: selectedDigest, err := fileutils.RestoreImageDigest(ctx, image, info)
137新增: if err != nil {
138新增: return fmt.Errorf("pinning the selected macOS restore image: %w", err)
139新增: }
140新增: template, err := os.CreateTemp("", "cage-macos-*.yaml")
141新增: if err != nil {
142新增: return err
143新增: }
144新增: defer os.Remove(template.Name())
145新增: location, err := json.Marshal(image)
146新增: if err == nil {
147新增: _, err = fmt.Fprintf(template, macOSInstallTemplate, location, selectedDigest)
148新增: }
149新增: closeErr := template.Close()
150新增: if err := errors.Join(err, closeErr); err != nil {
151新增: return err
152新增: }
153新增: settings.NoContainerd = true
154新增: if err := l.Create(ctx, name, template.Name(), settings, log); err != nil {
155新增: return err
156新增: }
157新增: requirements, err := macOSImageResourceRequirements(restore)
158新增: if err != nil {
159新增: return err
160新增: }
161新增: return saveMacOSResourceRequirements(filepath.Join(home, name), requirements)
162新增:}
163新增:
164新增:func applyMacOSRequirements(restore *vz.MacOSRestoreImage, settings *Settings) error {
165新增: requirements, err := macOSImageResourceRequirements(restore)
166新增: if err != nil {
167新增: return err
168新增: }
169新增: minCPU, minGiB := requirements.CPUs, requirements.MemoryGiB
170新增: if settings.CPUs == 0 {
171新增: settings.CPUs = minCPU
172新增: }
173新增: if settings.MemoryGiB == 0 {
174新增: settings.MemoryGiB = minGiB
175新增: }
176新增: if settings.CPUs < minCPU || settings.MemoryGiB < minGiB {
177新增: return fmt.Errorf("this macOS restore image requires at least %d CPUs and %d GiB RAM", minCPU, minGiB)
178新增: }
179新增: return nil
180新增:}
181新增:
182新增:const macOSInstallTemplate = `os: Darwin
183新增:arch: aarch64
184新增:vmType: vz
185新增:images:
186新增: - location: %s
187新增: arch: aarch64
188新增: digest: %s
189新增:user:
190新增: name: cageprovision
191新增: comment: Cage Provisioning
192新增: home: /Users/cageprovision
193新增: uid: 501
194新增:osOpts:
195新增: Darwin:
196新增: suppressFirstLoginSetup: true
197新增:provision:
198新增: - mode: system
199新增: script: |
200新增: #!/bin/sh
201新增: set -eu
202新增: [ "$(/usr/bin/uname -sm)" = "Darwin arm64" ]
203新增: case "$(/usr/sbin/sysctl -n hw.model)" in VirtualMac*,*) ;; *) exit 1 ;; esac
204新增: /usr/bin/ssh-keygen -A >/dev/null
205新增: # This serial port is attached by VZ to this specific private instance.
206新增: # Publish only the public key. SSH is pinned before provisioning begins.
207新增: /bin/echo "CAGE-GUEST-HOST-KEY $(/bin/cat /etc/ssh/ssh_host_ed25519_key.pub)" >/dev/tty.virtio
208新增:video:
209新增: display: offscreen
210新增:mounts: []
211新增:networks: []
212新增:ssh:
213新增: loadDotSSHPubKeys: false
214新增: forwardAgent: false
215新增: forwardX11: false
216新增:portForwards:
217新增: - guestIP: 0.0.0.0
218新增: guestIPMustBeZero: false
219新增: guestPortRange: [1, 65535]
220新增: proto: any
221新增: ignore: true
222新增:`
新增internal/vm/macos_install_darwin_arm64_test.go+130 −0看文件
@@ -0,0 +1,130 @@
1新增://go:build darwin && arm64 && cgo && !no_vz
2新增:
3新增:package vm
4新增:
5新增:import (
6新增: "errors"
7新增: "fmt"
8新增: "io"
9新增: "os"
10新增: "path/filepath"
11新增: "strings"
12新增: "testing"
13新增:
14新增: "github.com/Code-Hex/vz/v3"
15新增: "github.com/lima-vm/lima/v2/pkg/fileutils"
16新增: "github.com/lima-vm/lima/v2/pkg/limatype"
17新增: "github.com/lima-vm/lima/v2/pkg/limayaml"
18新增: "github.com/opencontainers/go-digest"
19新增:)
20新增:
21新增:func TestMacOSInstallSourceAndMounts(t *testing.T) {
22新增: l := &Lima{}
23新增: dir := t.TempDir()
24新增: t.Setenv("LIMA_HOME", filepath.Join(dir, "instances"))
25新增: ipsw := filepath.Join(dir, "bad.ipsw")
26新增: if err := os.WriteFile(ipsw, []byte("not a restore image"), 0o600); err != nil {
27新增: t.Fatal(err)
28新增: }
29新增: shares := []Mount{{Location: dir}}
30新增: for _, tc := range []struct {
31新增: file string
32新增: s Settings
33新增: want string
34新增: }{
35新增: {ipsw, Settings{Mounts: &shares}, "shared host directories"},
36新增: {"https://localhost/mac.ipsw", Settings{}, "absolute path"},
37新增: {ipsw, Settings{}, "Apple Virtualization"},
38新增: } {
39新增: if err := l.CreateMacOSFromIPSW(t.Context(), "mac", tc.file, tc.s, io.Discard); err == nil || !strings.Contains(err.Error(), tc.want) {
40新增: t.Fatalf("%q: expected %q, got %v", tc.file, tc.want, err)
41新增: }
42新增: }
43新增: t.Setenv("LIMA_HOME", dir)
44新增: if err := l.CreateMacOSFromIPSW(t.Context(), "mac", ipsw, Settings{}, io.Discard); err == nil || !strings.Contains(err.Error(), "outside") {
45新增: t.Fatalf("selected image in instance storage: %v", err)
46新增: }
47新增: if _, err := os.Stat(filepath.Join(dir, "mac")); !errors.Is(err, os.ErrNotExist) {
48新增: t.Fatalf("unexpected instance after preflight: %v", err)
49新增: }
50新增: if err := applyMacOSRequirements(&vz.MacOSRestoreImage{}, &Settings{}); err == nil {
51新增: t.Fatal("accepted an unsupported native restore image")
52新增: }
53新增:}
54新增:
55新增:func TestMacOSHostSourceCompatibility(t *testing.T) {
56新增: path := os.Getenv("CAGE_TEST_MACOS_SOURCE")
57新增: if path == "" {
58新增: t.Skip("set CAGE_TEST_MACOS_SOURCE to verified local restore media")
59新增: }
60新增: image, err := vz.LoadMacOSRestoreImageFromPath(path)
61新增: if err != nil {
62新增: t.Fatal(err)
63新增: }
64新增: settings := Settings{DiskGiB: 64}
65新增: if err := applyMacOSRequirements(image, &settings); err != nil {
66新增: t.Fatal(err)
67新增: }
68新增: t.Logf("Apple accepted the restore image, minimum CPUs=%d memoryGiB=%d", settings.CPUs, settings.MemoryGiB)
69新增:}
70新增:
71新增:func TestMacOSInstallTemplateIsolation(t *testing.T) {
72新增: expectedDigest := "sha256:" + strings.Repeat("a", 64)
73新增: body := fmt.Sprintf(macOSInstallTemplate, `"/example.ipsw"`, expectedDigest)
74新增: cfg, err := limayaml.Load(t.Context(), []byte(body), "macos.yaml")
75新增: if err != nil {
76新增: t.Fatal(err)
77新增: }
78新增: if err := limayaml.Validate(cfg, false); err != nil {
79新增: t.Fatal(err)
80新增: }
81新增: if len(cfg.Images) != 1 || cfg.Images[0].Digest.String() != expectedDigest {
82新增: t.Fatal("selected restore image digest was lost")
83新增: }
84新增: if cfg.User.Comment == nil || *cfg.User.Comment != "Cage Provisioning" || *cfg.User.Name != "cageprovision" || *cfg.User.Home != "/Users/cageprovision" {
85新增: t.Fatal("macOS template must not inherit the host account's full name")
86新增: }
87新增: var options limatype.DarwinOpts
88新增: if err := limayaml.Convert(cfg.OsOpts[limatype.DARWIN], &options, "osOpts.Darwin"); err != nil || options.SuppressFirstLoginSetup == nil || !*options.SuppressFirstLoginSetup {
89新增: t.Fatal("new guest did not prepare first-login settings", err)
90新增: }
91新增: if len(cfg.Mounts) != 0 || len(cfg.Networks) != 0 || *cfg.SSH.LoadDotSSHPubKeys || *cfg.SSH.ForwardAgent || *cfg.SSH.ForwardX11 {
92新增: t.Fatal("unexpected host sharing in macOS template")
93新增: }
94新增: if len(cfg.PortForwards) != 1 || !cfg.PortForwards[0].Ignore || cfg.PortForwards[0].GuestPortRange != [2]int{1, 65535} || cfg.PortForwards[0].Proto != "any" || *cfg.PortForwards[0].GuestIPMustBeZero {
95新增: t.Fatal("default guest port forwarding is not disabled")
96新增: }
97新增:}
98新增:
99新增:func TestSelectedIPSWRejectsReplacementAtSamePath(t *testing.T) {
100新增: dir := t.TempDir()
101新增: path := filepath.Join(dir, "selected.ipsw")
102新增: if err := os.WriteFile(path, []byte("original"), 0o600); err != nil {
103新增: t.Fatal(err)
104新增: }
105新增: selected, err := os.Stat(path)
106新增: if err != nil {
107新增: t.Fatal(err)
108新增: }
109新增: pin, err := fileutils.RestoreImageDigest(t.Context(), path, selected)
110新增: if err != nil || pin != digest.FromString("original") {
111新增: t.Fatalf("unexpected media pin: %s, %v", pin, err)
112新增: }
113新增: replacement := filepath.Join(dir, "renamed")
114新增: if err := os.WriteFile(replacement, []byte("replaced"), 0o600); err != nil {
115新增: t.Fatal(err)
116新增: }
117新增: if err := os.Chtimes(replacement, selected.ModTime(), selected.ModTime()); err != nil {
118新增: t.Fatal(err)
119新增: }
120新增: if err := os.Rename(replacement, path); err != nil {
121新增: t.Fatal(err)
122新增: }
123新增: if _, err := fileutils.RestoreImageDigest(t.Context(), path, selected); err == nil || !strings.Contains(err.Error(), "changed") {
124新增: t.Fatalf("accepted another inode with the original size and mtime: %v", err)
125新增: }
126新增: file := limatype.File{Location: path, Arch: limatype.AARCH64, Digest: pin}
127新增: if _, err := fileutils.DownloadFile(t.Context(), filepath.Join(dir, "image"), file, true, "restore image", limatype.AARCH64, nil); err == nil || !strings.Contains(err.Error(), "expected digest") {
128新增: t.Fatalf("Lima accepted replaced installation media: %v", err)
129新增: }
130新增:}
新增internal/vm/macos_project_e2e_test.go+96 −0看文件
@@ -0,0 +1,96 @@
1新增://go:build darwin && arm64 && cgo && e2e && !no_vz
2新增:
3新增:package vm
4新增:
5新增:import (
6新增: "bytes"
7新增: "context"
8新增: "errors"
9新增: "io"
10新增: "os"
11新增: "path/filepath"
12新增: "testing"
13新增: "time"
14新增:
15新增: "github.com/lima-vm/sshocker/pkg/reversesshfs"
16新增: "github.com/sylvinus/agent-vm/internal/mounts"
17新增: "golang.org/x/sys/unix"
18新增:)
19新增:
20新增:// Verify the workbench's restricted project service with the OpenSSH client
21新增:// shipped by Apple. The guest accesses the service only through its existing
22新增:// management SSH connection. This does not mount the project in the guest.
23新增:func verifyMacOSProjectTransfer(t *testing.T, ctx context.Context, l *Lima, name string) {
24新增: t.Helper()
25新增: project := t.TempDir()
26新增: if err := os.Mkdir(filepath.Join(project, ".git"), 0700); err != nil {
27新增: t.Fatal(err)
28新增: }
29新增: write := func(path, contents string, mode os.FileMode) {
30新增: t.Helper()
31新增: if err := os.WriteFile(filepath.Join(project, path), []byte(contents), mode); err != nil {
32新增: t.Fatal(err)
33新增: }
34新增: }
35新增: write(".git/HEAD", "ref: refs/heads/test\n", 0600)
36新增: write("build script", "#!/bin/sh\nprintf 'ran in guest'\n", 0755)
37新增: if err := os.Symlink("build script", filepath.Join(project, "build-link")); err != nil {
38新增: t.Fatal(err)
39新增: }
40新增:
41新增: fds, err := unix.Socketpair(unix.AF_UNIX, unix.SOCK_STREAM, 0)
42新增: if err != nil {
43新增: t.Fatal(err)
44新增: }
45新增: for _, fd := range fds {
46新增: unix.CloseOnExec(fd)
47新增: }
48新增: server := os.NewFile(uintptr(fds[0]), "project-server")
49新增: guest := os.NewFile(uintptr(fds[1]), "guest-ssh")
50新增: done := make(chan error, 1)
51新增: go func() {
52新增: defer server.Close()
53新增: done <- reversesshfs.ServeConfined(server, project, false, mounts.BaseNames)
54新增: }()
55新增: // nc relays only the SFTP protocol on SSH stdin/stdout. The client
56新增: // connects in a private guest directory. All diagnostics use stderr.
57新增: const script = `set -eu
58新增:umask 077
59新增:work=$(mktemp -d /tmp/cage-project.XXXXXXXX)
60新增:cd "$work"
61新增:exec 3<&0
62新增:/usr/bin/nc -lU wire <&3 3<&- &
63新增:relay=$!
64新增:exec 3<&- </dev/null >&2
65新增:trap 'kill "$relay" 2>/dev/null || :; wait "$relay" 2>/dev/null || :; rm -rf "$work"' EXIT
66新增:for ((i=0; i<100; i++)); do [[ -S wire ]] && break; sleep 0.05; done
67新增:test -S wire
68新增:printf 'guest save' > edit
69新增:cat > batch <<'EOF'
70新增:get -p build-link build
71新增:get .git/HEAD head-copy
72新增:put edit .saving
73新增:rename .saving "source file"
74新增:put edit .git/denied
75新增:EOF
76新增:if /usr/bin/sftp -q -b batch -D '/usr/bin/nc -U wire' unused; then exit 1; fi
77新增:test "$(cat head-copy)" = 'ref: refs/heads/test'
78新增:test "$(./build)" = 'ran in guest'`
79新增: ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
80新增: defer cancel()
81新增: var output bytes.Buffer
82新增: code, shellErr := l.Shell(ctx, name, ShellOpts{Args: []string{"/bin/bash", "-c", script}, Stdin: guest, Stdout: guest, Stderr: &output})
83新增: guest.Close()
84新增: serverErr := <-done
85新增: if code != 0 || shellErr != nil || (serverErr != nil && !errors.Is(serverErr, io.EOF)) {
86新增: t.Fatalf("guest transfer (%d): SSH %v, SFTP %v\n%s", code, shellErr, serverErr, output.String())
87新增: }
88新增: data, err := os.ReadFile(filepath.Join(project, "source file"))
89新增: if err != nil || string(data) != "guest save" {
90新增: t.Fatalf("guest atomic save did not reach the host: %v", err)
91新增: }
92新增: if _, err := os.Lstat(filepath.Join(project, ".git", "denied")); !errors.Is(err, os.ErrNotExist) {
93新增: t.Fatalf("guest protected write: %v", err)
94新增: }
95新增: t.Log("Guest SFTP executed a transferred script, saved to the host, and was denied a Git metadata write")
96新增:}
新增internal/vm/macos_resources.go+107 −0看文件
@@ -0,0 +1,107 @@
1新增:package vm
2新增:
3新增:import (
4新增: "bytes"
5新增: "encoding/json"
6新增: "errors"
7新增: "fmt"
8新增: "os"
9新增: "path/filepath"
10新增:
11新增: "github.com/docker/go-units"
12新增: "github.com/sylvinus/agent-vm/internal/cage"
13新增: "go.yaml.in/yaml/v3"
14新增:)
15新增:
16新增:// MacOSResourceRequirements belong to the installed guest, independent of the
17新增:// user's current allocation. Older guests retain their known bootable floor.
18新增:type MacOSResourceRequirements struct {
19新增: Version int `json:"version"`
20新增: MemoryGiB int `json:"minimum_memory_gib"`
21新增: CPUs int `json:"minimum_cpus"`
22新增: Source string `json:"source"`
23新增:}
24新增:
25新增:const macOSRequirementsFile = "cage-macos-resource-requirements.json"
26新增:
27新增:func (requirements MacOSResourceRequirements) Limits(allocation cage.ResourceAllocation) (int, int, error) {
28新增: memory, cpus, err := allocation.Limits()
29新增: if err != nil {
30新增: return 0, 0, err
31新增: }
32新增: if memory < requirements.MemoryGiB || cpus < requirements.CPUs {
33新增: return 0, 0, fmt.Errorf("这台 macOS 客机至少需要 %d GiB 内存与 %d 个 CPU 逻辑核心,请调整资源配置", requirements.MemoryGiB, requirements.CPUs)
34新增: }
35新增: return memory, cpus, nil
36新增:}
37新增:
38新增:func ReadMacOSResourceRequirements(instanceDir string) (MacOSResourceRequirements, error) {
39新增: var requirements MacOSResourceRequirements
40新增: data, err := os.ReadFile(filepath.Join(instanceDir, macOSRequirementsFile))
41新增: if err == nil {
42新增: if json.Unmarshal(data, &requirements) != nil || requirements.Version != 1 || requirements.MemoryGiB < 1 || requirements.CPUs < 1 ||
43新增: (requirements.Source != "restore-image" && requirements.Source != "existing-configuration") {
44新增: return requirements, errors.New("macOS 最低资源要求记录无效,请检查原环境配置")
45新增: }
46新增: if requirements.Source == "restore-image" {
47新增: return requirements, nil
48新增: }
49新增: }
50新增: if err != nil && !errors.Is(err, os.ErrNotExist) {
51新增: return requirements, errors.New("无法读取 macOS 最低资源要求记录")
52新增: }
53新增: data, err = os.ReadFile(filepath.Join(instanceDir, "lima.yaml"))
54新增: if err != nil {
55新增: return requirements, errors.New("无法读取这台 macOS 客机的启动配置")
56新增: }
57新增: var config struct {
58新增: OS string `yaml:"os"`
59新增: Memory string `yaml:"memory"`
60新增: CPUs int `yaml:"cpus"`
61新增: Images []struct {
62新增: Location string `yaml:"location"`
63新增: } `yaml:"images"`
64新增: }
65新增: if yaml.Unmarshal(data, &config) != nil || config.OS != "Darwin" {
66新增: return requirements, errors.New("macOS 客机启动配置无效")
67新增: }
68新增: candidates := []string{filepath.Join(instanceDir, "image.ipsw")}
69新增: if len(config.Images) == 1 && filepath.IsAbs(config.Images[0].Location) {
70新增: candidates = append(candidates, config.Images[0].Location)
71新增: }
72新增: for _, image := range candidates {
73新增: if info, err := os.Stat(image); err == nil && info.Mode().IsRegular() {
74新增: if requirements, err := macOSRestoreResourceRequirements(image); err == nil {
75新增: return requirements, nil
76新增: }
77新增: }
78新增: }
79新增: if requirements.Version == 1 {
80新增: return requirements, nil
81新增: }
82新增: memory, err := units.RAMInBytes(config.Memory)
83新增: if err != nil || memory < 1<<30 || config.CPUs < 1 {
84新增: return requirements, errors.New("无法确定已有 macOS 客机的可启动资源配置")
85新增: }
86新增: return MacOSResourceRequirements{Version: 1, MemoryGiB: int((memory-1)/(1<<30) + 1), CPUs: config.CPUs, Source: "existing-configuration"}, nil
87新增:}
88新增:
89新增:func saveMacOSResourceRequirements(instanceDir string, requirements MacOSResourceRequirements) error {
90新增: data, err := json.Marshal(requirements)
91新增: if err != nil {
92新增: return err
93新增: }
94新增: if current, err := os.ReadFile(filepath.Join(instanceDir, macOSRequirementsFile)); err == nil && bytes.Equal(current, data) {
95新增: return nil
96新增: }
97新增: file, err := os.CreateTemp(instanceDir, ".macos-resources-*")
98新增: if err != nil {
99新增: return err
100新增: }
101新增: defer os.Remove(file.Name())
102新增: _, err = file.Write(data)
103新增: if err = errors.Join(err, file.Close()); err != nil {
104新增: return err
105新增: }
106新增: return os.Rename(file.Name(), filepath.Join(instanceDir, macOSRequirementsFile))
107新增:}
新增internal/vm/macos_resources_darwin_arm64.go+32 −0看文件
@@ -0,0 +1,32 @@
1新增://go:build darwin && arm64 && cgo && !no_vz
2新增:
3新增:package vm
4新增:
5新增:import (
6新增: "errors"
7新增:
8新增: "github.com/Code-Hex/vz/v3"
9新增:)
10新增:
11新增:func macOSRestoreResourceRequirements(image string) (MacOSResourceRequirements, error) {
12新增: restore, err := vz.LoadMacOSRestoreImageFromPath(image)
13新增: if err != nil {
14新增: return MacOSResourceRequirements{}, err
15新增: }
16新增: return macOSImageResourceRequirements(restore)
17新增:}
18新增:
19新增:func macOSImageResourceRequirements(restore *vz.MacOSRestoreImage) (MacOSResourceRequirements, error) {
20新增: if restore == nil {
21新增: return MacOSResourceRequirements{}, errors.New("missing macOS restore image")
22新增: }
23新增: requirements := restore.MostFeaturefulSupportedConfiguration()
24新增: if requirements == nil || requirements.MinimumSupportedCPUCount() == 0 || requirements.MinimumSupportedMemorySize() == 0 {
25新增: return MacOSResourceRequirements{}, errors.New("this macOS restore image has no supported configuration for this Mac")
26新增: }
27新增: model := requirements.HardwareModel()
28新增: if model == nil || !model.Supported() || len(model.DataRepresentation()) == 0 {
29新增: return MacOSResourceRequirements{}, errors.New("this Mac does not support the restore image's hardware model")
30新增: }
31新增: return MacOSResourceRequirements{Version: 1, CPUs: int(requirements.MinimumSupportedCPUCount()), MemoryGiB: int((requirements.MinimumSupportedMemorySize()-1)/(1<<30) + 1), Source: "restore-image"}, nil
32新增:}
新增internal/vm/macos_resources_other.go+9 −0看文件
@@ -0,0 +1,9 @@
1新增://go:build !darwin || !arm64 || !cgo || no_vz
2新增:
3新增:package vm
4新增:
5新增:import "errors"
6新增:
7新增:func macOSRestoreResourceRequirements(string) (MacOSResourceRequirements, error) {
8新增: return MacOSResourceRequirements{}, errors.New("Apple 恢复镜像要求只能在 Apple Silicon Mac 上读取")
9新增:}
新增internal/vm/macos_resources_test.go+58 −0看文件
@@ -0,0 +1,58 @@
1新增:package vm
2新增:
3新增:import (
4新增: "os"
5新增: "path/filepath"
6新增: "testing"
7新增:
8新增: "github.com/sylvinus/agent-vm/internal/cage"
9新增: "github.com/sylvinus/agent-vm/internal/host"
10新增:)
11新增:
12新增:func TestMacOSResourceRequirementsPreserveExistingFloor(t *testing.T) {
13新增: directory := t.TempDir()
14新增: config := filepath.Join(directory, "lima.yaml")
15新增: if err := os.WriteFile(config, []byte("os: Darwin\nmemory: 8GiB\ncpus: 4\n"), 0600); err != nil {
16新增: t.Fatal(err)
17新增: }
18新增: requirements, err := ReadMacOSResourceRequirements(directory)
19新增: if err != nil || requirements.MemoryGiB != 8 || requirements.CPUs != 4 || requirements.Source != "existing-configuration" {
20新增: t.Fatalf("existing guest floor lost: %+v %v", requirements, err)
21新增: }
22新增: if err = saveMacOSResourceRequirements(directory, requirements); err != nil {
23新增: t.Fatal(err)
24新增: }
25新增: if err = os.WriteFile(config, []byte("os: Darwin\nmemory: 12GiB\ncpus: 6\n"), 0600); err != nil {
26新增: t.Fatal(err)
27新增: }
28新增: after, err := ReadMacOSResourceRequirements(directory)
29新增: if err != nil || after != requirements {
30新增: t.Fatalf("minimum drifted with allocation: %+v %v", after, err)
31新增: }
32新增: if err = os.WriteFile(filepath.Join(directory, macOSRequirementsFile), []byte(`{"version":1,"minimum_memory_gib":0}`), 0600); err != nil {
33新增: t.Fatal(err)
34新增: }
35新增: if _, err = ReadMacOSResourceRequirements(directory); err == nil {
36新增: t.Fatal("corrupt minimum silently accepted")
37新增: }
38新增:}
39新增:
40新增:func TestMacOSResourceRequirementsUseRestoreMinimumAndHostShare(t *testing.T) {
41新增: oldMemory, oldCPUs := host.MemGiB, host.CPUs
42新增: t.Cleanup(func() { host.MemGiB, host.CPUs = oldMemory, oldCPUs })
43新增: host.MemGiB = func() int { return 24 }
44新增: host.CPUs = func() int { return 10 }
45新增: t.Setenv("AGENT_VM_HOST_SHARE", "2")
46新增: requirements := MacOSResourceRequirements{Version: 1, MemoryGiB: 4, CPUs: 2, Source: "restore-image"}
47新增: for _, allocation := range []cage.ResourceAllocation{{MemoryGiB: 2, CPUs: 2}, {MemoryGiB: 4, CPUs: 1}, {MemoryGiB: 13, CPUs: 2}, {MemoryGiB: 4, CPUs: 6}} {
48新增: if _, _, err := requirements.Limits(allocation); err == nil {
49新增: t.Fatalf("accepted incompatible allocation %+v", allocation)
50新增: }
51新增: }
52新增: if memory, cpus, err := requirements.Limits(cage.ResourceAllocation{Automatic: true}); err != nil || memory != 12 || cpus != 5 {
53新增: t.Fatalf("automatic=%d/%d %v", memory, cpus, err)
54新增: }
55新增: if memory, cpus, err := requirements.Limits(cage.ResourceAllocation{MemoryGiB: 4, CPUs: 2}); err != nil || memory != 4 || cpus != 2 {
56新增: t.Fatalf("manual=%d/%d %v", memory, cpus, err)
57新增: }
58新增:}
新增internal/vm/start_error.go+81 −0看文件
@@ -0,0 +1,81 @@
1新增:package vm
2新增:
3新增:import (
4新增: "context"
5新增: "encoding/json"
6新增: "errors"
7新增: "fmt"
8新增: "io"
9新增: "os"
10新增: "path/filepath"
11新增: "strings"
12新增: "time"
13新增:
14新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
15新增:)
16新增:
17新增:// Keep the first QEMU stderr messages from this failed start visible through
18新增:// the CLI and desktop job, rather than only the later hostagent exit error.
19新增:func vmStartError(cause error, instanceDir string, since time.Time) error {
20新增: if cause == nil || errors.Is(cause, context.Canceled) {
21新增: return cause
22新增: }
23新增: f, err := os.Open(filepath.Join(instanceDir, "ha.stderr.log"))
24新增: if err != nil {
25新增: return cause
26新增: }
27新增: defer f.Close()
28新增: info, err := f.Stat()
29新增: if err != nil || info.ModTime().Before(since) {
30新增: return cause
31新增: }
32新增: if info.Size() > 64<<10 {
33新增: _, _ = f.Seek(info.Size()-(64<<10), io.SeekStart)
34新增: }
35新增: b, err := io.ReadAll(io.LimitReader(f, 64<<10))
36新增: if err != nil {
37新增: return cause
38新增: }
39新增: if info.Size() > 64<<10 {
40新增: // Never export a partial record cut through a credential or private key.
41新增: if next := strings.IndexByte(string(b), '\n'); next >= 0 {
42新增: b = b[next+1:]
43新增: } else {
44新增: b = nil
45新增: }
46新增: }
47新增: // Keep the bounded hostagent log available in the existing diagnostic
48新增: // export, including failures which happened before the guest could boot.
49新增: stream := diagnostics.NewStream(diagnostics.Default(), "vm/start", "error", nil)
50新增: _, _ = stream.Write(b)
51新增: _ = stream.Close()
52新增: var messages []string
53新增: for _, line := range strings.Split(string(b), "\n") {
54新增: var record struct {
55新增: Message string `json:"msg"`
56新增: }
57新增: if json.Unmarshal([]byte(line), &record) == nil && record.Message != "" {
58新增: line = record.Message
59新增: }
60新增: _, message, ok := strings.Cut(line, "qemu[stderr]")
61新增: if !ok {
62新增: continue
63新增: }
64新增: message = strings.TrimSpace(strings.TrimLeft(message, "]: \""))
65新增: if message == "" || strings.Contains(strings.ToLower(message), "warning:") {
66新增: continue
67新增: }
68新增: messages = append(messages, diagnostics.Redact(message))
69新增: if len(messages) == 6 {
70新增: break
71新增: }
72新增: }
73新增: if len(messages) == 0 {
74新增: return cause
75新增: }
76新增: summary := strings.Join(messages, ";")
77新增: if len(summary) > 2048 {
78新增: summary = strings.ToValidUTF8(summary[:2048], "")
79新增: }
80新增: return fmt.Errorf("QEMU 启动失败:%s;%w", summary, cause)
81新增:}
新增internal/vm/start_error_test.go+69 −0看文件
@@ -0,0 +1,69 @@
1新增:package vm
2新增:
3新增:import (
4新增: "archive/zip"
5新增: "bytes"
6新增: "context"
7新增: "errors"
8新增: "io"
9新增: "os"
10新增: "path/filepath"
11新增: "strings"
12新增: "testing"
13新增: "time"
14新增:
15新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
16新增:)
17新增:
18新增:func TestVMStartErrorPreservesQEMUFailureAndRedactsSecrets(t *testing.T) {
19新增: previous := diagnostics.Default()
20新增: store := diagnostics.New(t.TempDir())
21新增: diagnostics.SetDefault(store)
22新增: t.Cleanup(func() { diagnostics.SetDefault(previous) })
23新增: dir := t.TempDir()
24新增: log := strings.Repeat("{\"msg\":\"[qemu[stderr]] warning: host doesn't support requested feature\"}\n", 12) + `{"msg":"[qemu[stderr]] WHPX: Failed to enable nested virtualization, hr=80370302"}
25新增:{"msg":"[qemu[stderr]] failed to initialize whpx: Invalid argument token=private-test-value"}
26新增:panic: send on closed channel
27新增:`
28新增: if err := os.WriteFile(filepath.Join(dir, "ha.stderr.log"), []byte(log), 0600); err != nil {
29新增: t.Fatal(err)
30新增: }
31新增: cause := errors.New("host agent process has exited")
32新增: err := vmStartError(cause, dir, time.Time{})
33新增: if !errors.Is(err, cause) || !strings.Contains(err.Error(), "80370302") || strings.Contains(err.Error(), "private-test-value") || strings.Contains(err.Error(), "panic:") {
34新增: t.Fatalf("bad startup error: %v", err)
35新增: }
36新增: var bundle bytes.Buffer
37新增: if err := store.Export(&bundle, "test", nil, "guest never booted"); err != nil {
38新增: t.Fatal(err)
39新增: }
40新增: archive, err := zip.NewReader(bytes.NewReader(bundle.Bytes()), int64(bundle.Len()))
41新增: if err != nil {
42新增: t.Fatal(err)
43新增: }
44新增: var exported strings.Builder
45新增: for _, file := range archive.File {
46新增: if !strings.HasPrefix(file.Name, "logs/") {
47新增: continue
48新增: }
49新增: r, err := file.Open()
50新增: if err != nil {
51新增: t.Fatal(err)
52新增: }
53新增: data, err := io.ReadAll(r)
54新增: r.Close()
55新增: if err != nil {
56新增: t.Fatal(err)
57新增: }
58新增: exported.Write(data)
59新增: }
60新增: if text := exported.String(); !strings.Contains(text, "80370302") || !strings.Contains(text, "panic:") || strings.Contains(text, "private-test-value") {
61新增: t.Fatalf("diagnostic export lost details or exposed credentials: %s", text)
62新增: }
63新增: if vmStartError(context.Canceled, dir, time.Time{}) != context.Canceled {
64新增: t.Fatal("cancellation replaced by an old QEMU error")
65新增: }
66新增: if vmStartError(cause, dir, time.Now().Add(time.Second)) != cause {
67新增: t.Fatal("an earlier attempt's log replaced this failure")
68新增: }
69新增:}