| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | "time" |
| 12 | |
| 13 | "github.com/google/uuid" |
| 14 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 15 | ) |
| 16 | |
| 17 | |
| 18 | func init() { |
| 19 | if os.Getenv("CAGE_WINDOWS_CLI_RELAY_TEST") != "1" { |
| 20 | return |
| 21 | } |
| 22 | if len(os.Args) != 4 || os.Args[1] != "--relay-profile" || os.Args[3] != "cli" { |
| 23 | os.Exit(2) |
| 24 | } |
| 25 | var input map[string]json.RawMessage |
| 26 | if json.NewDecoder(os.Stdin).Decode(&input) != nil { |
| 27 | os.Exit(2) |
| 28 | } |
| 29 | var profile, action string |
| 30 | _ = json.Unmarshal(input["profile"], &profile) |
| 31 | _ = json.Unmarshal(input["action"], &action) |
| 32 | if len(profile) != 16 || input["command"] != nil { |
| 33 | os.Exit(2) |
| 34 | } |
| 35 | if stage := os.Getenv("CAGE_WINDOWS_CLI_RELAY_PROCESS_FAILURE"); stage != "" { |
| 36 | fmt.Fprintf(os.Stderr, "Windows guest channel unavailable (%s:IOException); private-token-must-not-appear\n", stage) |
| 37 | os.Exit(1) |
| 38 | } |
| 39 | if os.Getenv("CAGE_WINDOWS_CLI_RELAY_WARNING") == "1" { |
| 40 | fmt.Fprintln(os.Stderr, strings.Repeat("warning", 4096)) |
| 41 | } |
| 42 | if os.Getenv("CAGE_WINDOWS_CLI_RELAY_FAILURE") == "1" { |
| 43 | _ = json.NewEncoder(os.Stdout).Encode(map[string]any{"error": "requires_gui_login"}) |
| 44 | os.Exit(0) |
| 45 | } |
| 46 | switch action { |
| 47 | case "account": |
| 48 | if string(input["mode"]) != `"snapshot"` || string(input["account"]) != `"default"` { |
| 49 | os.Exit(2) |
| 50 | } |
| 51 | _ = json.NewEncoder(os.Stdout).Encode(map[string]any{"logged_in": false}) |
| 52 | case "channel": |
| 53 | if os.Getenv("CAGE_WINDOWS_CLI_RELAY_MOBILE") == "1" { |
| 54 | var mode string |
| 55 | _ = json.Unmarshal(input["mode"], &mode) |
| 56 | var query map[string]any |
| 57 | if json.Unmarshal(input["input"], &query) != nil || query["workspace"] != os.Getenv("CAGE_WINDOWS_CLI_RELAY_WORKSPACE") || query["project_id"] != strings.Repeat("a", 16) || query["grant"] != strings.Repeat("b", 64) { |
| 58 | os.Exit(2) |
| 59 | } |
| 60 | if capture := os.Getenv("CAGE_WINDOWS_CLI_RELAY_CAPTURE"); capture != "" { |
| 61 | file, err := os.OpenFile(capture, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) |
| 62 | if err != nil { |
| 63 | os.Exit(2) |
| 64 | } |
| 65 | _ = json.NewEncoder(file).Encode(map[string]any{"mode": mode, "input": query}) |
| 66 | _ = file.Close() |
| 67 | } |
| 68 | if marker := os.Getenv("CAGE_WINDOWS_CLI_RELAY_BLOCK"); marker != "" { |
| 69 | if os.WriteFile(marker, []byte("started"), 0600) != nil { |
| 70 | os.Exit(2) |
| 71 | } |
| 72 | time.Sleep(time.Minute) |
| 73 | } |
| 74 | var result any = map[string]any{"ok": true} |
| 75 | if mode == "view" { |
| 76 | result = terminalConversation{CLIID: query["cli_id"].(string), Connection: query["connection"].(string), Config: query["config"].(string), Workspace: query["workspace"].(string), Running: true, CanSend: true, ChannelReady: true, Turns: []mobileTurn{}} |
| 77 | } |
| 78 | _ = json.NewEncoder(os.Stdout).Encode(map[string]any{"result": result}) |
| 79 | break |
| 80 | } |
| 81 | _ = json.NewEncoder(os.Stdout).Encode(map[string]any{"result": []any{}}) |
| 82 | default: |
| 83 | os.Exit(2) |
| 84 | } |
| 85 | os.Exit(0) |
| 86 | } |
| 87 | func windowsCLIRelayFixture(t *testing.T) *Server { |
| 88 | t.Helper() |
| 89 | s := testServer(t) |
| 90 | binding := guestos.WindowsProfile{Version: 1, VMID: uuid.New(), GUIUserSID: "S-1-5-21-123-456-789-1001", GUIUser: "Guest", InstanceDirectory: filepath.Join(s.profile, "vm"), PairingFile: filepath.Join(s.profile, "pair.dpapi"), RelayExecutable: os.Args[0]} |
| 91 | if err := guestos.BindWindowsProfile(s.profile, binding); err != nil { |
| 92 | t.Fatal(err) |
| 93 | } |
| 94 | s.windowsGuest = &binding |
| 95 | t.Setenv("CAGE_WINDOWS_CLI_RELAY_TEST", "1") |
| 96 | return s |
| 97 | } |
| 98 | func TestWindowsCLINativeReportAndArrayTransport(t *testing.T) { |
| 99 | s := windowsCLIRelayFixture(t) |
| 100 | result, err := s.readWindowsClaudeAccount(context.Background(), "snapshot", "default", "") |
| 101 | if err != nil || result.LoggedIn { |
| 102 | t.Fatalf("native account report failed: %v", err) |
| 103 | } |
| 104 | var sessions []terminalConversation |
| 105 | if err := s.windowsCLIRequest(context.Background(), map[string]any{"action": "channel", "mode": "discover", "input": map[string]any{"accounts": []string{"default"}, "workspaces": map[string]string{}}}, &sessions); err != nil || sessions == nil { |
| 106 | t.Fatalf("native array response failed: %v", err) |
| 107 | } |
| 108 | } |
| 109 | func TestWindowsCLIRejectsRevokedAndSiblingWorkspace(t *testing.T) { |
| 110 | s := windowsCLIRelayFixture(t) |
| 111 | path := `C:\Users\Guest\Cage\Projects\` + strings.Repeat("a", 16) |
| 112 | share := &projectShare{windowsProject: &windowsProjectBinding{ID: strings.Repeat("a", 16), Grant: strings.Repeat("b", 64), Path: path}, done: make(chan struct{})} |
| 113 | s.projectShares = map[string]*projectShare{"authorized": share} |
| 114 | for _, bad := range []string{path + `-other`, path + `\..\private`} { |
| 115 | if err := s.windowsCLIRequest(context.Background(), map[string]any{"action": "channel", "mode": "handoff", "input": map[string]any{"workspace": bad}}, new(any)); err == nil { |
| 116 | t.Fatal("unmapped guest workspace admitted") |
| 117 | } |
| 118 | } |
| 119 | close(share.done) |
| 120 | if err := s.windowsCLIRequest(context.Background(), map[string]any{"action": "channel", "mode": "handoff", "input": map[string]any{"workspace": path}}, new(any)); err == nil { |
| 121 | t.Fatal("revoked guest project admitted") |
| 122 | } |
| 123 | if !cliWorkspaceWithin(path+`\nested`, strings.ToLower(path), true) || cliWorkspaceWithin(path+`-other`, path, true) { |
| 124 | t.Fatal("Windows workspace separator or case changed authorization") |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | func TestWindowsCLIRPCFailureCannotSignAnAccountOut(t *testing.T) { |
| 129 | s := windowsCLIRelayFixture(t) |
| 130 | t.Setenv("CAGE_WINDOWS_CLI_RELAY_FAILURE", "1") |
| 131 | if _, err := s.readWindowsClaudeAccount(context.Background(), "snapshot", "default", ""); err == nil || !strings.Contains(err.Error(), "Windows 桌面尚未登录或已锁定") { |
| 132 | t.Fatalf("GUI/RPC failure lost its login explanation: %v", err) |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | func TestWindowsCLIProcessFailureExplainsStageWithoutLeakingStderr(t *testing.T) { |
| 137 | s := windowsCLIRelayFixture(t) |
| 138 | for _, test := range []struct{ stage, message string }{ |
| 139 | {"profile", "无法读取 Windows 环境配置"}, |
| 140 | {"pairing", "安全配对校验未完成"}, |
| 141 | {"connect", "未能连接 Windows 会话服务"}, |
| 142 | {"transfer", "通信未完成"}, |
| 143 | {"unknown", "未能读取 Windows 会话服务的响应"}, |
| 144 | } { |
| 145 | t.Run(test.stage, func(t *testing.T) { |
| 146 | t.Setenv("CAGE_WINDOWS_CLI_RELAY_PROCESS_FAILURE", test.stage) |
| 147 | err := s.windowsCLIRequest(context.Background(), map[string]any{"action": "channel", "mode": "discover"}, new(any)) |
| 148 | if err == nil || !strings.Contains(err.Error(), test.message) || strings.Contains(err.Error(), "private-token") || strings.Contains(err.Error(), "官方账号") { |
| 149 | t.Fatalf("relay failure was misclassified or exposed stderr: %v", err) |
| 150 | } |
| 151 | }) |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | func TestWindowsCLIRequestTimeoutExplainsDeadline(t *testing.T) { |
| 156 | s := windowsCLIRelayFixture(t) |
| 157 | ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) |
| 158 | defer cancel() |
| 159 | err := s.windowsCLIRequest(ctx, map[string]any{"action": "channel", "mode": "discover"}, new(any)) |
| 160 | if err == nil || !strings.Contains(err.Error(), "响应超时") { |
| 161 | t.Fatalf("request timeout lost its cause: %v", err) |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | func TestWindowsCLILongStderrDoesNotFailSuccessfulRequest(t *testing.T) { |
| 166 | s := windowsCLIRelayFixture(t) |
| 167 | t.Setenv("CAGE_WINDOWS_CLI_RELAY_WARNING", "1") |
| 168 | if _, err := s.readWindowsClaudeAccount(context.Background(), "snapshot", "default", ""); err != nil { |
| 169 | t.Fatalf("helper warning broke a successful response: %v", err) |
| 170 | } |
| 171 | } |