| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "encoding/base64" |
| 8 | "encoding/json" |
| 9 | "fmt" |
| 10 | "image" |
| 11 | "image/jpeg" |
| 12 | "image/png" |
| 13 | "os" |
| 14 | "path/filepath" |
| 15 | "strings" |
| 16 | "testing" |
| 17 | "time" |
| 18 | |
| 19 | "github.com/google/uuid" |
| 20 | "github.com/sylvinus/agent-vm/internal/cage" |
| 21 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 22 | ) |
| 23 | |
| 24 | |
| 25 | |
| 26 | func init() { |
| 27 | directory := os.Getenv("CAGE_TEST_WINDOWS_PHONE_WINDOW") |
| 28 | if directory == "" { |
| 29 | return |
| 30 | } |
| 31 | if len(os.Args) != 4 || os.Args[1] != "--relay-profile" || os.Args[3] != "desktop" { |
| 32 | os.Exit(2) |
| 33 | } |
| 34 | capture, _ := os.OpenFile(filepath.Join(directory, "requests.jsonl"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) |
| 35 | defer capture.Close() |
| 36 | reader := bufio.NewScanner(os.Stdin) |
| 37 | reader.Buffer(make([]byte, 65536), 128<<10) |
| 38 | width, height := 800, 600 |
| 39 | for reader.Scan() { |
| 40 | var input map[string]any |
| 41 | if json.Unmarshal(reader.Bytes(), &input) != nil { |
| 42 | os.Exit(3) |
| 43 | } |
| 44 | _, _ = capture.Write(append(append([]byte{}, reader.Bytes()...), '\n')) |
| 45 | control := map[string]any{} |
| 46 | if data, err := os.ReadFile(filepath.Join(directory, "control.json")); err == nil { |
| 47 | _ = json.Unmarshal(data, &control) |
| 48 | } |
| 49 | target := "window-geometry" |
| 50 | if changed, ok := control["target"].(string); ok { |
| 51 | target = changed |
| 52 | } |
| 53 | reply := map[string]any{"ok": true} |
| 54 | switch input["action"] { |
| 55 | case "status": |
| 56 | reply = map[string]any{"installed": control["missing"] != true, "running": control["stopped"] != true, "phone_supported": control["legacy"] != true, "display_scale": 1.25} |
| 57 | case "resize": |
| 58 | width, height = max(800, int(input["width"].(float64))), max(600, int(input["height"].(float64))) |
| 59 | case "frame": |
| 60 | sequence := fmt.Sprintf("%s-%dx%d", target, width, height) |
| 61 | if input["after"] == sequence { |
| 62 | reply = map[string]any{"unchanged": true, "sequence": sequence} |
| 63 | } else { |
| 64 | var encoded bytes.Buffer |
| 65 | _ = png.Encode(&encoded, image.NewRGBA(image.Rect(0, 0, width, height))) |
| 66 | reply = map[string]any{"target": target, "width": width, "height": height, "density": 1.25, "sequence": sequence, "png": base64.StdEncoding.EncodeToString(encoded.Bytes())} |
| 67 | } |
| 68 | case "ime": |
| 69 | reply = map[string]any{"available": control["no_focus"] != true, "context": "editable-focus", "password": control["password"] == true} |
| 70 | case "pointer", "key", "text": |
| 71 | if input["target"] != target { |
| 72 | reply = map[string]any{"error": "desktop_target_changed"} |
| 73 | } |
| 74 | if input["phone_focus"] != nil && (control["no_focus"] == true || control["password"] == true || input["phone_focus"] != "editable-focus") { |
| 75 | reply = map[string]any{"error": "desktop_phone_focus_changed"} |
| 76 | } |
| 77 | } |
| 78 | if control["locked"] == true { |
| 79 | reply = map[string]any{"error": "requires_gui_login"} |
| 80 | } |
| 81 | _ = json.NewEncoder(os.Stdout).Encode(reply) |
| 82 | } |
| 83 | _ = os.WriteFile(filepath.Join(directory, "closed"), []byte("relay closed"), 0600) |
| 84 | os.Exit(0) |
| 85 | } |
| 86 | |
| 87 | func windowsPhoneDesktopFixture(t *testing.T) (*Server, string, *cage.EgressGate) { |
| 88 | t.Helper() |
| 89 | s := testServer(t) |
| 90 | directory := t.TempDir() |
| 91 | binding := guestos.WindowsProfile{Version: 1, VMID: uuid.New(), GUIUserSID: "S-1-5-21-1-2-3-1001", GUIUser: "Guest", InstanceDirectory: filepath.Join(s.profile, "unused-vm"), PairingFile: filepath.Join(s.profile, "unused-pair"), RelayExecutable: os.Args[0]} |
| 92 | if err := guestos.BindWindowsProfile(s.profile, binding); err != nil { |
| 93 | t.Fatal(err) |
| 94 | } |
| 95 | s.windowsGuest = &binding |
| 96 | if err := os.MkdirAll(binding.InstanceDirectory, 0700); err != nil { |
| 97 | t.Fatal(err) |
| 98 | } |
| 99 | s.ready = true |
| 100 | room, cancel := context.WithCancel(t.Context()) |
| 101 | s.phones.roomCtx, s.phones.roomProof = room, "phone-window-room" |
| 102 | s.phones.serving = cancel |
| 103 | s.phones.record = &phoneRecord{} |
| 104 | t.Setenv("CAGE_TEST_WINDOWS_PHONE_WINDOW", directory) |
| 105 | t.Cleanup(func() { |
| 106 | cancel() |
| 107 | s.phones.desktop.op.Lock() |
| 108 | defer s.phones.desktop.op.Unlock() |
| 109 | s.retirePhoneSurface(phoneDesktop, s.phones.desktop.session) |
| 110 | }) |
| 111 | cfg, err := loadConfig(s.configPath) |
| 112 | if err != nil { |
| 113 | t.Fatal(err) |
| 114 | } |
| 115 | gate, err := cage.NewEgressGate(cfg) |
| 116 | if err != nil { |
| 117 | t.Fatal(err) |
| 118 | } |
| 119 | stop, err := cage.StartGateControl(s.configPath, s.instanceDir(), gate) |
| 120 | if err != nil { |
| 121 | t.Fatal(err) |
| 122 | } |
| 123 | t.Cleanup(stop) |
| 124 | if err := gate.BeginCheck(); err != nil { |
| 125 | t.Fatal(err) |
| 126 | } |
| 127 | state := gate.Status() |
| 128 | report := cage.SafetyReport{Policy: cage.SafetyPolicyVersion, ID: "windows-phone-test", RunID: state.RunID, CheckID: state.CheckID, Configuration: state.Configuration, CreatedAt: time.Now()} |
| 129 | for _, check := range []string{"egress_policy", "proxy_transport", "dns_transport", "guest_settings", "browser_settings", "filesystem_boundary", "management_boundary", "fail_closed", "udp_policy", "ipv6_policy", "exit_consistency"} { |
| 130 | report.Checks = append(report.Checks, cage.SafetyCheck{ID: check, Critical: true, State: cage.CheckPassed, Evidence: "isolated fixture", CheckedAt: report.CreatedAt}) |
| 131 | } |
| 132 | if err := gate.Grant(report); err != nil { |
| 133 | t.Fatal(err) |
| 134 | } |
| 135 | return s, directory, gate |
| 136 | } |
| 137 | |
| 138 | func TestWindowsPhoneDesktopProductionHandlerSharesWindowAndGuardsInput(t *testing.T) { |
| 139 | s, directory, _ := windowsPhoneDesktopFixture(t) |
| 140 | id := uuid.NewString() |
| 141 | base := "/api/mobile/desktop/" + id |
| 142 | open := fmt.Sprintf(`{"id":%q,"width":390,"height":640,"pixel_ratio":2}`, id) |
| 143 | if got := windowsPhoneRequest(t, s, "POST", "/api/mobile/desktop/open", open, "old-room"); got.Code != 403 { |
| 144 | t.Fatalf("old room: %d", got.Code) |
| 145 | } |
| 146 | if got := windowsPhoneRequest(t, s, "POST", "/api/mobile/desktop/open", open, "phone-window-room"); got.Code != 200 { |
| 147 | t.Fatalf("open: %d %s", got.Code, got.Body.String()) |
| 148 | } |
| 149 | readFrame := func() map[string]any { |
| 150 | t.Helper() |
| 151 | got := windowsPhoneRequest(t, s, "GET", base+"/frame", "", "phone-window-room") |
| 152 | var frame map[string]any |
| 153 | if got.Code != 200 || json.Unmarshal(got.Body.Bytes(), &frame) != nil { |
| 154 | t.Fatalf("frame: %d %s", got.Code, got.Body.String()) |
| 155 | } |
| 156 | return frame |
| 157 | } |
| 158 | frame := readFrame() |
| 159 | if frame["shared"] != true || frame["login_supported"] != false || frame["pixel_ratio_supported"] != true || frame["focus"] != "editable-focus" || frame["content_width"] != float64(640) || frame["content_height"] != float64(640) { |
| 160 | t.Fatalf("shared frame contract: %v", frame) |
| 161 | } |
| 162 | encoded, err := base64.StdEncoding.DecodeString(frame["image"].(string)) |
| 163 | if err != nil || len(encoded) > 2<<20 { |
| 164 | t.Fatal("invalid encoded image") |
| 165 | } |
| 166 | geometry, err := jpeg.DecodeConfig(bytes.NewReader(encoded)) |
| 167 | if err != nil || geometry.Width > 780 || geometry.Height > 1280 { |
| 168 | t.Fatalf("JPEG geometry: %+v %v", geometry, err) |
| 169 | } |
| 170 | if cached := readFrame(); cached["image"] != frame["image"] { |
| 171 | t.Fatal("static frame cache changed") |
| 172 | } |
| 173 | if err := os.WriteFile(filepath.Join(directory, "control.json"), []byte(`{"password":true}`), 0600); err != nil { |
| 174 | t.Fatal(err) |
| 175 | } |
| 176 | if password := readFrame(); password["focus"] != "" || password["password"] != true { |
| 177 | t.Fatal("password field accepted phone typing") |
| 178 | } |
| 179 | if err := os.WriteFile(filepath.Join(directory, "control.json"), []byte(`{}`), 0600); err != nil { |
| 180 | t.Fatal(err) |
| 181 | } |
| 182 | readFrame() |
| 183 | post := func(body map[string]any, want int) { |
| 184 | t.Helper() |
| 185 | data, _ := json.Marshal(body) |
| 186 | got := windowsPhoneRequest(t, s, "POST", base+"/action", string(data), "phone-window-room") |
| 187 | if got.Code != want { |
| 188 | t.Fatalf("action %v: %d %s", body["type"], got.Code, got.Body.String()) |
| 189 | } |
| 190 | } |
| 191 | post(map[string]any{"type": "tap", "document": "old-geometry", "x": 10, "y": 10}, 409) |
| 192 | post(map[string]any{"type": "tap", "document": frame["document"], "x": 639, "y": 639}, 200) |
| 193 | post(map[string]any{"type": "scroll", "document": frame["document"], "x": 400, "y": 400, "dx": -120, "dy": 240}, 200) |
| 194 | post(map[string]any{"type": "text", "document": frame["document"], "focus": "old-focus", "text": "ignored"}, 409) |
| 195 | post(map[string]any{"type": "text", "document": frame["document"], "focus": frame["focus"], "text": strings.Repeat("中", 2730) + "ab"}, 200) |
| 196 | post(map[string]any{"type": "key", "document": frame["document"], "focus": frame["focus"], "key": "Enter"}, 200) |
| 197 | post(map[string]any{"type": "resize", "width": 800, "height": 600, "pixel_ratio": 1.5}, 200) |
| 198 | resized := readFrame() |
| 199 | if resized["width"] != float64(800) || resized["content_width"] != float64(800) || resized["requested_pixel_ratio"] != 1.5 { |
| 200 | t.Fatal("resize contract lost") |
| 201 | } |
| 202 | |
| 203 | |
| 204 | if err := os.WriteFile(filepath.Join(directory, "control.json"), []byte(`{"no_focus":true}`), 0600); err != nil { |
| 205 | t.Fatal(err) |
| 206 | } |
| 207 | post(map[string]any{"type": "text", "document": resized["document"], "focus": resized["focus"], "text": "must reject"}, 409) |
| 208 | requests, _ := os.ReadFile(filepath.Join(directory, "requests.jsonl")) |
| 209 | if !bytes.Contains(requests, []byte(`"phone_focus":"editable-focus"`)) || !bytes.Contains(requests, []byte(`"mask":1`)) || !bytes.Contains(requests, []byte(`"mask":0`)) { |
| 210 | t.Fatal("native input guard or release missing") |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | func TestWindowsPhoneDesktopReadinessAndCapabilities(t *testing.T) { |
| 215 | for _, test := range []struct { |
| 216 | name, control string |
| 217 | want int |
| 218 | }{{"legacy", `{"legacy":true}`, 426}, {"missing", `{"missing":true}`, 501}, {"locked", `{"locked":true}`, 410}} { |
| 219 | t.Run(test.name, func(t *testing.T) { |
| 220 | s, directory, _ := windowsPhoneDesktopFixture(t) |
| 221 | _ = os.WriteFile(filepath.Join(directory, "control.json"), []byte(test.control), 0600) |
| 222 | body := fmt.Sprintf(`{"id":%q,"width":390,"height":640}`, uuid.NewString()) |
| 223 | got := windowsPhoneRequest(t, s, "POST", "/api/mobile/desktop/open", body, "phone-window-room") |
| 224 | if got.Code != test.want { |
| 225 | t.Fatalf("%s: %d %s", test.name, got.Code, got.Body.String()) |
| 226 | } |
| 227 | if test.name == "locked" && !strings.Contains(got.Body.String(), "Windows 客机账户") { |
| 228 | t.Fatal("locked GUI did not explain how to recover") |
| 229 | } |
| 230 | if s.phones.desktop.nativeDesktop != nil || s.phones.desktop.session != nil { |
| 231 | t.Fatal("failed open retained native lease") |
| 232 | } |
| 233 | }) |
| 234 | } |
| 235 | s, _, gate := windowsPhoneDesktopFixture(t) |
| 236 | s.windowsState = windowsGuestState{Available: true, ComponentsChecked: time.Now(), Capabilities: []string{"desktop"}, Components: map[string]windowsComponentState{"phone-desktop": {Supported: true, Registered: true, Installed: true, Ready: true}}} |
| 237 | status := gate.Status() |
| 238 | s.safety.Gate = &status |
| 239 | if !s.windowsCapabilitiesLocked()["available"].(map[string]bool)["phone-desktop"] { |
| 240 | t.Fatal("ready supported desktop unavailable") |
| 241 | } |
| 242 | s.networkPaused = true |
| 243 | if s.windowsCapabilitiesLocked()["available"].(map[string]bool)["phone-desktop"] { |
| 244 | t.Fatal("paused network advertised phone desktop") |
| 245 | } |
| 246 | s.networkPaused = false |
| 247 | s.windowsState.Available = false |
| 248 | if s.windowsCapabilitiesLocked()["available"].(map[string]bool)["phone-desktop"] { |
| 249 | t.Fatal("locked GUI advertised phone desktop") |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | func TestWindowsPhoneDesktopRevocationClosesNativeRelay(t *testing.T) { |
| 254 | s, directory, _ := windowsPhoneDesktopFixture(t) |
| 255 | id := uuid.NewString() |
| 256 | body := fmt.Sprintf(`{"id":%q,"width":390,"height":640}`, id) |
| 257 | got := windowsPhoneRequest(t, s, "POST", "/api/mobile/desktop/open", body, "phone-window-room") |
| 258 | if got.Code != 200 { |
| 259 | t.Fatalf("open: %d %s", got.Code, got.Body.String()) |
| 260 | } |
| 261 | native := s.phones.desktop.nativeDesktop |
| 262 | s.stopPhone() |
| 263 | deadline := time.Now().Add(3 * time.Second) |
| 264 | for { |
| 265 | s.phones.desktop.op.Lock() |
| 266 | closed := s.phones.desktop.session == nil && s.phones.desktop.nativeDesktop == nil |
| 267 | s.phones.desktop.op.Unlock() |
| 268 | if closed { |
| 269 | break |
| 270 | } |
| 271 | if time.Now().After(deadline) { |
| 272 | t.Fatal("revocation retained the native relay") |
| 273 | } |
| 274 | time.Sleep(time.Millisecond) |
| 275 | } |
| 276 | if native.connection.cmd.ProcessState == nil { |
| 277 | t.Fatal("revocation did not reap the relay process") |
| 278 | } |
| 279 | if got := windowsPhoneRequest(t, s, "GET", "/api/mobile/desktop/"+id+"/frame", "", "phone-window-room"); got.Code != 403 { |
| 280 | t.Fatalf("revoked room: %d", got.Code) |
| 281 | } |
| 282 | requests, _ := os.ReadFile(filepath.Join(directory, "requests.jsonl")) |
| 283 | if bytes.Contains(requests, []byte(`"action":"stop"`)) { |
| 284 | t.Fatal("phone close stopped the shared desktop application") |
| 285 | } |
| 286 | } |