| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "slices" |
| 12 | "strconv" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | |
| 16 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 17 | ) |
| 18 | |
| 19 | func TestMacOSConnectionIgnoresSSHConfigOverrides(t *testing.T) { |
| 20 | s := testServer(t) |
| 21 | s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "devuser"} |
| 22 | if err := os.MkdirAll(s.instanceDir(), 0700); err != nil { |
| 23 | t.Fatal(err) |
| 24 | } |
| 25 | cfg := "Host lima-mac\n User root\n HostName 192.0.2.1\n Port 54432\n ProxyCommand false\n StrictHostKeyChecking no\n ForwardAgent yes\n" |
| 26 | if err := os.WriteFile(filepath.Join(s.instanceDir(), "ssh.config"), []byte(cfg), 0600); err != nil { |
| 27 | t.Fatal(err) |
| 28 | } |
| 29 | cmd := s.sshCommand(context.Background(), "-tt", s.sshTarget(), "--", "uname -s") |
| 30 | for _, value := range []string{os.DevNull, "54432", "devuser", "Hostname=127.0.0.1", "HostKeyAlias=cage-macos", "StrictHostKeyChecking=yes", "ForwardAgent=no", "ClearAllForwardings=yes", "cage-macos"} { |
| 31 | if !slices.Contains(cmd.Args, value) { |
| 32 | t.Errorf("bound SSH missing %q", value) |
| 33 | } |
| 34 | } |
| 35 | for _, value := range []string{"192.0.2.1", "root", "ForwardAgent=yes", "StrictHostKeyChecking=no", "lima-mac"} { |
| 36 | if slices.Contains(cmd.Args, value) { |
| 37 | t.Errorf("untrusted override %q used", value) |
| 38 | } |
| 39 | } |
| 40 | if !slices.Contains(cmd.Args, "UserKnownHostsFile="+strconv.Quote(filepath.Join(s.profile, "macos-known-hosts"))) { |
| 41 | t.Fatal("missing profile-scoped host key") |
| 42 | } |
| 43 | for _, bad := range []string{"", "Port 0", "Port 65536", "Port 22\nPort 23", "Port 22 -o Anything"} { |
| 44 | if _, err := guestos.MacOSSSHPort([]byte(bad)); err == nil { |
| 45 | t.Errorf("accepted %q", bad) |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | func TestMacOSWorkbenchLocalViewIsolation(t *testing.T) { |
| 51 | s := testServer(t) |
| 52 | s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "guestdev"} |
| 53 | h := s.handler() |
| 54 | check := func(path string, trusted bool, want int) { |
| 55 | t.Helper() |
| 56 | r := httptest.NewRequest("GET", s.origin+path, nil) |
| 57 | r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session}) |
| 58 | if trusted { |
| 59 | r.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)}) |
| 60 | } |
| 61 | w := httptest.NewRecorder() |
| 62 | h.ServeHTTP(w, r) |
| 63 | if w.Code != want { |
| 64 | t.Errorf("%s trusted=%v: got %d; want %d", path, trusted, w.Code, want) |
| 65 | } |
| 66 | if path == "/api/account" && trusted && !strings.Contains(w.Body.String(), `"guest_system":"macos"`) { |
| 67 | t.Fatal("trusted view did not select the macOS workbench") |
| 68 | } |
| 69 | } |
| 70 | check("/api/account", false, http.StatusForbidden) |
| 71 | check("/api/account", true, http.StatusOK) |
| 72 | r := httptest.NewRequest("GET", s.origin+"/api/account", nil) |
| 73 | r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session}) |
| 74 | r.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)}) |
| 75 | w := httptest.NewRecorder() |
| 76 | h.ServeHTTP(w, r) |
| 77 | var account accountView |
| 78 | if err := json.Unmarshal(w.Body.Bytes(), &account); err != nil || account.MacOSGuestUser != "guestdev" { |
| 79 | t.Fatalf("actual guest login was not returned: %s", w.Body.String()) |
| 80 | } |
| 81 | |
| 82 | check("/api/browser/tabs", true, http.StatusConflict) |
| 83 | check("/api/proxy", false, http.StatusForbidden) |
| 84 | check("/api/mobile/pair", true, http.StatusConflict) |
| 85 | } |
| 86 | |
| 87 | func TestMacOSReadyBrowserRoutesUseNativeGuest(t *testing.T) { |
| 88 | s := testServer(t) |
| 89 | s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "guestdev"} |
| 90 | s.ready = true |
| 91 | s.windowsBrowserControl = fixtureWindowsBrowserClient(t) |
| 92 | r := windowsBrowserRequestForTest(s, http.MethodGet, "/api/browser/tabs", nil) |
| 93 | if r.Code != http.StatusOK || !json.Valid(r.Body.Bytes()) || s.browserControl != nil { |
| 94 | t.Fatalf("ready Mac browser failed to use the native transport: %d", r.Code) |
| 95 | } |
| 96 | if !macOSWorkbenchRoute("/api/input/files/browser/chunks") || macOSWorkbenchRoute("/api/input/files/desktop/chunks") { |
| 97 | t.Fatal("native browser upload route boundary mismatch") |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | func TestMacOSProjectRejectsSiblingProfileAndCredentials(t *testing.T) { |
| 102 | home := t.TempDir() |
| 103 | t.Setenv("HOME", home) |
| 104 | t.Setenv("USERPROFILE", home) |
| 105 | profile := filepath.Join(home, ".claude-cage", "macos-trial") |
| 106 | dailyState := filepath.Join(home, ".claude-cage", "state", "lima") |
| 107 | credentials := filepath.Join(home, ".ssh") |
| 108 | project := filepath.Join(home, "Cage Projects", "demo") |
| 109 | for _, dir := range []string{profile, dailyState, credentials, project} { |
| 110 | if err := os.MkdirAll(dir, 0700); err != nil { |
| 111 | t.Fatal(err) |
| 112 | } |
| 113 | } |
| 114 | s := &Server{profile: profile, macosGuest: &guestos.MacOSProfile{User: "guestdev"}} |
| 115 | for _, dir := range []string{dailyState, credentials} { |
| 116 | if err := s.ensureProjectShare(dir); err == nil || !strings.Contains(err.Error(), "共享") { |
| 117 | t.Fatalf("%s was not rejected before contacting the guest: %v", dir, err) |
| 118 | } |
| 119 | } |
| 120 | if err := validateHostProjectData(project, profile); err != nil { |
| 121 | t.Fatal(err) |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | func TestMacOSProjectApprovalIsBoundToOnePendingShare(t *testing.T) { |
| 126 | s := testServer(t) |
| 127 | s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "guestdev"} |
| 128 | s.ready = true |
| 129 | folder := t.TempDir() |
| 130 | share := &projectShare{} |
| 131 | s.projectShares = map[string]*projectShare{folder: share} |
| 132 | s.beginMacOSProjectApproval(folder, share) |
| 133 | grant := share.approval |
| 134 | t.Cleanup(func() { share.approvalTimer.Stop() }) |
| 135 | call := func(path, proof string) int { |
| 136 | t.Helper() |
| 137 | body, _ := json.Marshal(map[string]string{"workspace": path, "grant": proof, "action": "cancel"}) |
| 138 | r := httptest.NewRequest("POST", s.origin+"/api/macos/project-approval", bytes.NewReader(body)) |
| 139 | r.Header.Set("Content-Type", "application/json") |
| 140 | r.Header.Set("Origin", s.origin) |
| 141 | r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session}) |
| 142 | r.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)}) |
| 143 | w := httptest.NewRecorder() |
| 144 | s.handler().ServeHTTP(w, r) |
| 145 | return w.Code |
| 146 | } |
| 147 | if call(folder, "invalid") != http.StatusConflict || call(folder+"/other", grant) != http.StatusConflict || s.projectShares[folder] != share { |
| 148 | t.Fatal("unrelated approval canceled the pending host share") |
| 149 | } |
| 150 | if call(folder, grant) != 200 || s.projectShares[folder] != nil || call(folder, grant) != http.StatusConflict { |
| 151 | t.Fatal("a canceled project grant can still be reused") |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | func TestInitialMacSetupQuarantinesRegularWorkbench(t *testing.T) { |
| 156 | s := testServer(t) |
| 157 | s.macosGuest = &guestos.MacOSProfile{User: "cageuser", Instance: "mac", SetupID: "new"} |
| 158 | |
| 159 | |
| 160 | for _, path := range []string{"/api/browser/tabs", "/api/terminals", "/api/macos/login", "/api/projects/open", "/api/safety/check", "/api/macos/claude/window"} { |
| 161 | w := request(s, "GET", path, s.origin, "", true) |
| 162 | if w.Code != http.StatusConflict { |
| 163 | t.Errorf("setup exposed %s: %d", path, w.Code) |
| 164 | } |
| 165 | } |
| 166 | s.macosGuest.SetupID = "" |
| 167 | for _, action := range []string{"open", "finish", "frame", "fill-password"} { |
| 168 | req := httptest.NewRequest("POST", s.origin+"/api/macos/first-setup", strings.NewReader(`{"action":"`+action+`"}`)) |
| 169 | req.Header.Set("Origin", s.origin) |
| 170 | req.Header.Set("Content-Type", "application/json") |
| 171 | req.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session}) |
| 172 | req.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)}) |
| 173 | w := httptest.NewRecorder() |
| 174 | s.handler().ServeHTTP(w, req) |
| 175 | if w.Code != http.StatusGone { |
| 176 | t.Errorf("completed setup allowed %s: %d", action, w.Code) |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | func TestMacOSSetupAdministratorIdentity(t *testing.T) { |
| 182 | for _, user := range []string{"cage", "cageprovision"} { |
| 183 | t.Run(user, func(t *testing.T) { |
| 184 | s := testServer(t) |
| 185 | s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "cage"} |
| 186 | if err := os.MkdirAll(s.instanceDir(), 0700); err != nil { |
| 187 | t.Fatal(err) |
| 188 | } |
| 189 | if err := os.WriteFile(filepath.Join(s.instanceDir(), "ssh.config"), []byte("User "+user+"\nPort 12345\n"), 0600); err != nil { |
| 190 | t.Fatal(err) |
| 191 | } |
| 192 | cmd := s.macOSSetupAdminCommand(t.Context()) |
| 193 | if cmd.Err != nil { |
| 194 | t.Fatal(cmd.Err) |
| 195 | } |
| 196 | if !slices.Contains(cmd.Args, user) || cmd.Args[len(cmd.Args)-1] != "exec /usr/bin/sudo -S -p '' /usr/local/libexec/cage-finish-initial-setup < /Users/"+user+"/password" { |
| 197 | t.Fatalf("incorrect setup identity: %v", cmd.Args) |
| 198 | } |
| 199 | }) |
| 200 | } |
| 201 | } |