| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "github.com/sylvinus/agent-vm/internal/host" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | |
| 14 | "github.com/sylvinus/agent-vm/internal/cage" |
| 15 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 16 | ) |
| 17 | |
| 18 | func testServer(t *testing.T) *Server { |
| 19 | t.Helper() |
| 20 | profile := t.TempDir() |
| 21 | path := filepath.Join(profile, "config.json") |
| 22 | c := cage.DefaultConfig() |
| 23 | p, _ := managedproxy.Load(profile) |
| 24 | p.Auth = strings.Repeat("secret", 8) |
| 25 | if err := p.Import("test", "", []byte(`proxies: [{name: qa, type: socks5, server: 127.0.0.1, port: 1}]`), "source", 0, ""); err != nil { |
| 26 | t.Fatal(err) |
| 27 | } |
| 28 | p.Selected = p.Sources[0].Nodes[0].ID |
| 29 | p.Revision = "test-revision" |
| 30 | if err := p.Save(profile); err != nil { |
| 31 | t.Fatal(err) |
| 32 | } |
| 33 | c.ProxyURL = p.Endpoint() |
| 34 | c.ProxyRevision = p.Revision |
| 35 | if e := writePrivate(path, c); e != nil { |
| 36 | t.Fatal(e) |
| 37 | } |
| 38 | |
| 39 | |
| 40 | account := &localAccount{path: filepath.Join(profile, "account.json"), record: &accountRecord{Version: 1, Username: "Test"}} |
| 41 | account.setKey(make([]byte, 32)) |
| 42 | t.Cleanup(account.lock) |
| 43 | return &Server{account: account, profile: profile, configPath: path, origin: "http://localhost:17777", token: strings.Repeat("a", 64), session: strings.Repeat("b", 64), preferences: Preferences{Keyboard: "mac"}} |
| 44 | } |
| 45 | |
| 46 | |
| 47 | |
| 48 | func (s *Server) setJobForTest(job Job) { |
| 49 | s.jobs.mu.Lock() |
| 50 | defer s.jobs.mu.Unlock() |
| 51 | s.jobs.state = job |
| 52 | } |
| 53 | |
| 54 | func request(s *Server, method, path, origin, body string, auth bool) *httptest.ResponseRecorder { |
| 55 | r := httptest.NewRequest(method, s.origin+path, strings.NewReader(body)) |
| 56 | if origin != "" { |
| 57 | r.Header.Set("Origin", origin) |
| 58 | } |
| 59 | r.Header.Set("Content-Type", "application/json") |
| 60 | if auth { |
| 61 | r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session}) |
| 62 | } |
| 63 | w := httptest.NewRecorder() |
| 64 | s.handler().ServeHTTP(w, r) |
| 65 | return w |
| 66 | } |
| 67 | func TestHostManagementBoundary(t *testing.T) { |
| 68 | s := testServer(t) |
| 69 | if w := request(s, "GET", "/api/settings", "", "", false); w.Code != 401 { |
| 70 | t.Fatalf("unauthenticated settings: %d", w.Code) |
| 71 | } |
| 72 | for _, origin := range []string{"", "http://127.0.0.1:18080", "https://attacker.example"} { |
| 73 | if w := request(s, "POST", "/api/start", origin, "{}", true); w.Code != 403 { |
| 74 | t.Fatalf("cross-origin %q: %d", origin, w.Code) |
| 75 | } |
| 76 | } |
| 77 | r := httptest.NewRequest("GET", "http://rebind.example:17777/api/status", nil) |
| 78 | r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session}) |
| 79 | w := httptest.NewRecorder() |
| 80 | s.handler().ServeHTTP(w, r) |
| 81 | if w.Code != 403 { |
| 82 | t.Fatalf("DNS rebinding Host accepted: %d", w.Code) |
| 83 | } |
| 84 | w = request(s, "GET", "/api/settings", "", "", true) |
| 85 | if w.Code != 200 { |
| 86 | t.Fatal(w.Code, w.Body.String()) |
| 87 | } |
| 88 | if strings.Contains(w.Body.String(), strings.Repeat("secret", 8)) || strings.Contains(w.Body.String(), "proxy_url") { |
| 89 | t.Fatal("password returned to UI") |
| 90 | } |
| 91 | if w.Header().Get("Access-Control-Allow-Origin") != "" { |
| 92 | t.Fatal("CORS unexpectedly enabled") |
| 93 | } |
| 94 | if !strings.Contains(w.Header().Get("Content-Security-Policy"), "frame-src 'none'") { |
| 95 | t.Fatal("guest frames allowed") |
| 96 | } |
| 97 | } |
| 98 | func TestBootstrapRequiresSecretAndIssuesHostOnlyCookie(t *testing.T) { |
| 99 | s := testServer(t) |
| 100 | if w := request(s, "POST", "/api/session", s.origin, `{"token":"wrong"}`, false); w.Code != 401 { |
| 101 | t.Fatal(w.Code) |
| 102 | } |
| 103 | if w := request(s, "POST", "/api/session", s.origin, `{"token":"`+s.token+`"}{}`, false); w.Code != 400 { |
| 104 | t.Fatal("extra JSON accepted") |
| 105 | } |
| 106 | ticket := s.issueTicket() |
| 107 | w := request(s, "POST", "/api/session", s.origin, `{"token":"`+ticket+`"}`, false) |
| 108 | if w.Code != 200 { |
| 109 | t.Fatal(w.Code) |
| 110 | } |
| 111 | if replay := request(s, "POST", "/api/session", s.origin, `{"token":"`+ticket+`"}`, false); replay.Code != 401 { |
| 112 | t.Fatal("bootstrap ticket may be replayed") |
| 113 | } |
| 114 | cookies := w.Result().Cookies() |
| 115 | if len(cookies) != 1 { |
| 116 | t.Fatal("missing cookie") |
| 117 | } |
| 118 | c := cookies[0] |
| 119 | if !c.HttpOnly || c.SameSite != http.SameSiteStrictMode || c.Domain != "" { |
| 120 | t.Fatalf("unsafe cookie attributes: %+v", c) |
| 121 | } |
| 122 | } |
| 123 | func TestSettingsPreserveSecretsAndRejectHostSharing(t *testing.T) { |
| 124 | s := testServer(t) |
| 125 | old, e := cage.Load(s.configPath) |
| 126 | if e != nil { |
| 127 | t.Fatal(e) |
| 128 | } |
| 129 | input := settingsView(old, s.preferences) |
| 130 | input.Keyboard = "native" |
| 131 | next, _, e := proposedSettings(input, old, s.profile) |
| 132 | if e != nil { |
| 133 | t.Fatal(e) |
| 134 | } |
| 135 | if next.ProxyURL != old.ProxyURL { |
| 136 | t.Fatal("blank password erased existing authentication") |
| 137 | } |
| 138 | input.Workspace = s.profile |
| 139 | if _, _, e = proposedSettings(input, old, s.profile); e == nil { |
| 140 | t.Fatal("profile may be shared") |
| 141 | } |
| 142 | input.Workspace = filepath.Dir(s.profile) |
| 143 | if _, _, e = proposedSettings(input, old, s.profile); e == nil { |
| 144 | t.Fatal("profile ancestor may be shared") |
| 145 | } |
| 146 | workspace := t.TempDir() |
| 147 | link := filepath.Join(workspace, "private-link") |
| 148 | if e = os.Symlink(s.profile, link); e != nil { |
| 149 | t.Fatal(e) |
| 150 | } |
| 151 | input.Workspace = link |
| 152 | if _, _, e = proposedSettings(input, old, s.profile); e == nil { |
| 153 | t.Fatal("symlink bypassed share guard") |
| 154 | } |
| 155 | } |
| 156 | func TestInvalidSettingsDoNotReplaceCurrentProfile(t *testing.T) { |
| 157 | s := testServer(t) |
| 158 | before, _ := os.ReadFile(s.configPath) |
| 159 | old, _ := cage.Load(s.configPath) |
| 160 | input := settingsView(old, s.preferences) |
| 161 | input.Timezone = "Invented/Invalid" |
| 162 | body, _ := json.Marshal(input) |
| 163 | w := request(s, "POST", "/api/settings", s.origin, string(body), true) |
| 164 | if w.Code != 400 { |
| 165 | t.Fatal(w.Code) |
| 166 | } |
| 167 | after, _ := os.ReadFile(s.configPath) |
| 168 | if string(before) != string(after) { |
| 169 | t.Fatal("invalid save changed profile") |
| 170 | } |
| 171 | } |
| 172 | func TestKeyboardPreferenceDoesNotRestartOrChangeNetwork(t *testing.T) { |
| 173 | s := testServer(t) |
| 174 | old, _ := cage.Load(s.configPath) |
| 175 | s.ready = true |
| 176 | p := s.preferences |
| 177 | p.Keyboard = "native" |
| 178 | if e := s.apply(savedProfile{old, p}, true); e != nil { |
| 179 | t.Fatal(e) |
| 180 | } |
| 181 | after, _ := cage.Load(s.configPath) |
| 182 | if after != old || !s.ready { |
| 183 | t.Fatal("keyboard-only save changed runtime") |
| 184 | } |
| 185 | b, _ := os.ReadFile(filepath.Join(s.profile, "workbench.json")) |
| 186 | var saved Preferences |
| 187 | _ = json.Unmarshal(b, &saved) |
| 188 | if saved.Keyboard != "native" { |
| 189 | t.Fatal("preference not persisted") |
| 190 | } |
| 191 | if host.CheckPrivateFile(s.configPath) != nil { |
| 192 | t.Fatal("profile permissions") |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | func TestDisplayPreferenceAppliesAtNextLaunch(t *testing.T) { |
| 197 | s := testServer(t) |
| 198 | cfg, err := cage.Load(s.configPath) |
| 199 | if err != nil { |
| 200 | t.Fatal(err) |
| 201 | } |
| 202 | s.ready = true |
| 203 | s.credentials.DisplayScale = 2 |
| 204 | p := s.preferences |
| 205 | p.BalancedDisplay = true |
| 206 | if err := s.apply(savedProfile{cfg, p}, true); err != nil { |
| 207 | t.Fatal(err) |
| 208 | } |
| 209 | |
| 210 | w := request(s, "GET", "/api/vnc-credentials", "", "", true) |
| 211 | var active struct { |
| 212 | Scale float64 `json:"display_scale"` |
| 213 | Dynamic bool `json:"dynamic_scale"` |
| 214 | } |
| 215 | if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &active) != nil || active.Scale != 2 || active.Dynamic { |
| 216 | t.Fatal("reconnect lost the running display density") |
| 217 | } |
| 218 | |
| 219 | s.credentials.DynamicScale = true |
| 220 | w = request(s, "GET", "/api/vnc-credentials", "", "", true) |
| 221 | if json.Unmarshal(w.Body.Bytes(), &active) != nil || !active.Dynamic { |
| 222 | t.Fatal("viewer was not told that the display follows its screen") |
| 223 | } |
| 224 | |
| 225 | settings := request(s, "GET", "/api/settings", "", "", true) |
| 226 | var payload map[string]any |
| 227 | if err = json.Unmarshal(settings.Body.Bytes(), &payload); err != nil || payload["balanced_display"] != true { |
| 228 | t.Fatal("saved display preference unavailable") |
| 229 | } |
| 230 | delete(payload, "balanced_display") |
| 231 | body, _ := json.Marshal(payload) |
| 232 | r := httptest.NewRequest("POST", "/api/settings", strings.NewReader(string(body))) |
| 233 | r.Header.Set("Content-Type", "application/json") |
| 234 | next, ok := s.proposed(httptest.NewRecorder(), r) |
| 235 | if !ok || !next.Preferences.BalancedDisplay || next.Config != cfg { |
| 236 | t.Fatal("legacy settings save changed the display preference or network configuration") |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | func TestLocationProbeHasNoDirectFallback(t *testing.T) { |
| 241 | c := cage.DefaultConfig() |
| 242 | c.ProxyURL = "socks5://127.0.0.1:1" |
| 243 | if _, e := probeLocation(context.Background(), c); e == nil { |
| 244 | t.Fatal("location probe bypassed unavailable proxy") |
| 245 | } |
| 246 | } |
| 247 | func TestLocationLiveIntegration(t *testing.T) { |
| 248 | path := os.Getenv("CAGE_TEST_CONFIG") |
| 249 | if path == "" { |
| 250 | t.Skip("explicit proxy profile required") |
| 251 | } |
| 252 | c, e := cage.Load(path) |
| 253 | if e != nil { |
| 254 | t.Fatal(e) |
| 255 | } |
| 256 | loc, e := probeLocation(context.Background(), c) |
| 257 | if e != nil { |
| 258 | t.Fatal(e) |
| 259 | } |
| 260 | if loc.IP == "" || loc.Timezone == "" { |
| 261 | t.Fatal("missing location") |
| 262 | } |
| 263 | t.Log("Proxy geolocation returned a valid IP and IANA timezone; sensitive values omitted") |
| 264 | } |
| 265 | |
| 266 | func TestRestoreCannotReplaceManagedEndpoint(t *testing.T) { |
| 267 | s := testServer(t) |
| 268 | s.ready = true |
| 269 | old, _ := cage.Load(s.configPath) |
| 270 | bad := old |
| 271 | bad.ProxyURL = "socks5://127.0.0.1:1" |
| 272 | if e := s.apply(savedProfile{bad, s.preferences}, true); e != nil { |
| 273 | t.Fatal(e) |
| 274 | } |
| 275 | after, _ := loadConfig(s.configPath) |
| 276 | if after != old || !s.ready { |
| 277 | t.Fatal("restore changed the managed endpoint or interrupted the environment") |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | func TestSSHIsolationOverridesLocalClientSettings(t *testing.T) { |
| 282 | if _, err := os.Stat(sshExecutable()); err != nil { |
| 283 | t.Skip("OpenSSH is required") |
| 284 | } |
| 285 | s := testServer(t) |
| 286 | s.preferences.Workspace = t.TempDir() |
| 287 | dir := filepath.Join(s.profile, "state", "lima", cage.InstanceName(s.profile, s.environmentDir())) |
| 288 | if err := os.MkdirAll(dir, 0700); err != nil { |
| 289 | t.Fatal(err) |
| 290 | } |
| 291 | config := "Host *\n BatchMode no\n ForwardAgent yes\n ForwardX11 yes\n PermitLocalCommand yes\n EscapeChar ~\n PasswordAuthentication yes\n" |
| 292 | if err := os.WriteFile(filepath.Join(dir, "ssh.config"), []byte(config), 0600); err != nil { |
| 293 | t.Fatal(err) |
| 294 | } |
| 295 | t.Setenv("CAGE_TEST_HOST_SECRET", "must-not-cross-the-boundary") |
| 296 | cmd := s.sshCommand(context.Background(), "-G", "lima-test") |
| 297 | if cmd.Env == nil { |
| 298 | t.Fatal("SSH inherits the host environment") |
| 299 | } |
| 300 | for _, v := range cmd.Env { |
| 301 | if strings.HasPrefix(v, "CAGE_TEST_HOST_SECRET=") { |
| 302 | t.Fatal("host secret forwarded") |
| 303 | } |
| 304 | } |
| 305 | out, err := cmd.Output() |
| 306 | if err != nil { |
| 307 | t.Fatal(err) |
| 308 | } |
| 309 | effective := strings.ToLower(string(out)) |
| 310 | for _, expected := range []string{"batchmode yes", "forwardagent no", "forwardx11 no", "permitlocalcommand no", "escapechar none", "passwordauthentication no"} { |
| 311 | if !strings.Contains(effective, expected) { |
| 312 | t.Errorf("SSH effective configuration lacks %q", expected) |
| 313 | } |
| 314 | } |
| 315 | } |
| 316 | func TestImplicitHostTimezonesAreRejected(t *testing.T) { |
| 317 | for _, zone := range []string{"", "Local"} { |
| 318 | c := cage.DefaultConfig() |
| 319 | c.Timezone = zone |
| 320 | if c.Validate() == nil { |
| 321 | t.Errorf("implicit timezone %q accepted", zone) |
| 322 | } |
| 323 | } |
| 324 | } |