| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "mime" |
| 7 | "net/http" |
| 8 | "net/http/httputil" |
| 9 | "net/url" |
| 10 | "runtime" |
| 11 | "strings" |
| 12 | "sync" |
| 13 | |
| 14 | "github.com/sylvinus/agent-vm/internal/remotehost" |
| 15 | ) |
| 16 | |
| 17 | const connectionHeader = "X-Cage-Connection" |
| 18 | |
| 19 | type remoteGateway struct { |
| 20 | mu sync.Mutex |
| 21 | remote bool |
| 22 | clientOnly bool |
| 23 | clientShares map[string]*clientProjectGrant |
| 24 | store *remotehost.Store |
| 25 | manager *remotehost.Manager |
| 26 | desktop *desktopGateway |
| 27 | } |
| 28 | |
| 29 | func newRemoteGateway(profile string) *remoteGateway { |
| 30 | store := remotehost.NewStore(profile) |
| 31 | return &remoteGateway{store: store, manager: remotehost.NewManager(store)} |
| 32 | } |
| 33 | |
| 34 | func (g *remoteGateway) close() { |
| 35 | if g.desktop != nil { |
| 36 | g.desktop.close() |
| 37 | } |
| 38 | _ = g.manager.Close() |
| 39 | g.drainClosedClientShares() |
| 40 | } |
| 41 | |
| 42 | func (g *remoteGateway) isRemote() bool { |
| 43 | g.mu.Lock() |
| 44 | defer g.mu.Unlock() |
| 45 | return g.remote |
| 46 | } |
| 47 | |
| 48 | func (g *remoteGateway) setRemote(remote bool) { |
| 49 | g.mu.Lock() |
| 50 | g.remote = remote |
| 51 | g.mu.Unlock() |
| 52 | } |
| 53 | |
| 54 | type ClientContext struct { |
| 55 | DesktopGateway bool `json:"desktop_gateway,omitempty"` |
| 56 | Candidate *desktopCandidate `json:"candidate,omitempty"` |
| 57 | ClientOnly bool `json:"client_only"` |
| 58 | Mode string `json:"mode"` |
| 59 | ClientPlatform string `json:"client_platform"` |
| 60 | ConnectionID string `json:"connection_id"` |
| 61 | State remotehost.ConnectionState `json:"connection"` |
| 62 | InstanceID string `json:"instance_id,omitempty"` |
| 63 | HostID string `json:"host_id,omitempty"` |
| 64 | HostFingerprint string `json:"host_fingerprint,omitempty"` |
| 65 | ServerPlatform string `json:"server_platform"` |
| 66 | Name string `json:"name,omitempty"` |
| 67 | } |
| 68 | |
| 69 | func (g *remoteGateway) context() ClientContext { |
| 70 | if g.desktop != nil { |
| 71 | return g.desktop.context() |
| 72 | } |
| 73 | result := ClientContext{Mode: "local", ConnectionID: "local", ClientPlatform: runtime.GOOS, ServerPlatform: runtime.GOOS} |
| 74 | result.ClientOnly = g.clientOnly |
| 75 | result.State = g.manager.Snapshot() |
| 76 | if !g.isRemote() { |
| 77 | return result |
| 78 | } |
| 79 | result.Mode, result.ConnectionID = "remote", result.State.ConnectionID |
| 80 | result.HostID, result.InstanceID = result.State.HostID, result.State.InstanceID |
| 81 | result.ServerPlatform = "linux" |
| 82 | if hosts, err := g.store.List(); err == nil { |
| 83 | for _, host := range hosts { |
| 84 | if host.ID == result.HostID { |
| 85 | result.Name = host.Name |
| 86 | if host.HostKey != nil { |
| 87 | result.HostFingerprint = host.HostKey.Fingerprint |
| 88 | } |
| 89 | break |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | return result |
| 94 | } |
| 95 | |
| 96 | func (s *Server) clientRequest(w http.ResponseWriter, r *http.Request) { |
| 97 | g := s.remote |
| 98 | if g == nil { |
| 99 | http.Error(w, "远程连接服务不可用", 503) |
| 100 | return |
| 101 | } |
| 102 | path := strings.TrimPrefix(r.URL.Path, "/api/client/") |
| 103 | if path == "browser-extensions" && (r.Method == http.MethodGet || r.Method == http.MethodPost) { |
| 104 | s.localBrowserExtensions(w, r) |
| 105 | return |
| 106 | } |
| 107 | if path == "project-shares" || strings.HasPrefix(path, "project-shares/") { |
| 108 | s.clientProjectShareRequest(w, r, path) |
| 109 | return |
| 110 | } |
| 111 | if path == "commit" || path == "disconnect" || path == "local" { |
| 112 | defer g.drainClosedClientShares() |
| 113 | } |
| 114 | if g.desktop != nil && g.desktop.handle(path, w, r) { |
| 115 | return |
| 116 | } |
| 117 | switch { |
| 118 | case r.Method == "GET" && path == "context": |
| 119 | jsonReply(w, g.context()) |
| 120 | case r.Method == "GET" && path == "connection": |
| 121 | jsonReply(w, g.context().State) |
| 122 | case r.Method == "GET" && path == "hosts": |
| 123 | hosts, err := g.store.List() |
| 124 | if err != nil { |
| 125 | requestError(w, err) |
| 126 | return |
| 127 | } |
| 128 | jsonReply(w, map[string]any{"hosts": hosts}) |
| 129 | case (r.Method == "POST" && path == "hosts") || (r.Method == "PUT" && strings.HasPrefix(path, "hosts/")): |
| 130 | var host remotehost.HostProfile |
| 131 | if !readJSON(w, r, &host) { |
| 132 | return |
| 133 | } |
| 134 | if r.Method == "PUT" { |
| 135 | host.ID = strings.TrimPrefix(path, "hosts/") |
| 136 | } else { |
| 137 | host.ID = "" |
| 138 | } |
| 139 | if g.desktop != nil { |
| 140 | g.desktop.change.Lock() |
| 141 | defer g.desktop.change.Unlock() |
| 142 | } |
| 143 | if host.ID != "" && g.hostInUse(host.ID) { |
| 144 | http.Error(w, "请先断开这台主机,再修改连接配置", 409) |
| 145 | return |
| 146 | } |
| 147 | saved, err := g.store.Upsert(host) |
| 148 | if err != nil { |
| 149 | requestError(w, err) |
| 150 | return |
| 151 | } |
| 152 | jsonReply(w, saved) |
| 153 | case r.Method == "DELETE" && strings.HasPrefix(path, "hosts/"): |
| 154 | id := strings.TrimPrefix(path, "hosts/") |
| 155 | if g.desktop != nil { |
| 156 | g.desktop.change.Lock() |
| 157 | defer g.desktop.change.Unlock() |
| 158 | } |
| 159 | if g.hostInUse(id) { |
| 160 | http.Error(w, "请先断开这台主机,再删除本机连接配置", 409) |
| 161 | return |
| 162 | } |
| 163 | if err := g.store.Delete(id); err != nil { |
| 164 | requestError(w, err) |
| 165 | return |
| 166 | } |
| 167 | jsonReply(w, map[string]bool{"ok": true}) |
| 168 | case r.Method == "POST" && path == "connect": |
| 169 | var input struct { |
| 170 | HostID string `json:"host_id"` |
| 171 | Deploy bool `json:"deploy,omitempty"` |
| 172 | Passphrase string `json:"passphrase"` |
| 173 | } |
| 174 | if !readJSON(w, r, &input) { |
| 175 | return |
| 176 | } |
| 177 | secret := []byte(input.Passphrase) |
| 178 | input.Passphrase = "" |
| 179 | state, err := g.manager.Connect(input.HostID, remotehost.ConnectSecrets{Passphrase: secret, Deploy: input.Deploy}) |
| 180 | clear(secret) |
| 181 | if err != nil { |
| 182 | clear(secret) |
| 183 | requestError(w, err) |
| 184 | return |
| 185 | } |
| 186 | g.setRemote(true) |
| 187 | w.WriteHeader(http.StatusAccepted) |
| 188 | jsonReply(w, state) |
| 189 | case r.Method == "POST" && (path == "disconnect" || path == "local"): |
| 190 | if path == "local" && g.clientOnly { |
| 191 | http.Error(w, "轻量客户端仅连接远程环境", 409) |
| 192 | return |
| 193 | } |
| 194 | var input struct { |
| 195 | ConnectionID string `json:"connection_id"` |
| 196 | } |
| 197 | if !readJSON(w, r, &input) { |
| 198 | return |
| 199 | } |
| 200 | if err := g.manager.Disconnect(input.ConnectionID); err != nil { |
| 201 | requestError(w, err) |
| 202 | return |
| 203 | } |
| 204 | if path == "local" { |
| 205 | g.setRemote(false) |
| 206 | } |
| 207 | jsonReply(w, g.context()) |
| 208 | default: |
| 209 | http.NotFound(w, r) |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | func (g *remoteGateway) hostInUse(id string) bool { |
| 214 | c := g.context() |
| 215 | inUse := func(state remotehost.ConnectionState) bool { |
| 216 | return state.HostID == id && (state.State == "connecting" || state.State == "connected") |
| 217 | } |
| 218 | return inUse(c.State) || (c.Candidate != nil && inUse(c.Candidate.Connection)) |
| 219 | } |
| 220 | |
| 221 | func requestConnection(r *http.Request) string { |
| 222 | if value := r.Header.Get(connectionHeader); value != "" { |
| 223 | return value |
| 224 | } |
| 225 | return r.URL.Query().Get("connection") |
| 226 | } |
| 227 | |
| 228 | |
| 229 | |
| 230 | |
| 231 | func (s *Server) routeRemote(w http.ResponseWriter, r *http.Request) bool { |
| 232 | if s.remote == nil || !strings.HasPrefix(r.URL.Path, "/api/") { |
| 233 | return false |
| 234 | } |
| 235 | if strings.HasPrefix(r.URL.Path, "/api/client/") { |
| 236 | s.clientRequest(w, r) |
| 237 | return true |
| 238 | } |
| 239 | switch r.URL.Path { |
| 240 | case "/api/session", "/api/launch", "/api/handoff": |
| 241 | return false |
| 242 | case "/api/remote/manifest": |
| 243 | if s.remote.desktop != nil { |
| 244 | http.NotFound(w, r) |
| 245 | return true |
| 246 | } |
| 247 | return false |
| 248 | } |
| 249 | if r.URL.Path == "/api/diagnostics/events" { |
| 250 | return false |
| 251 | } |
| 252 | var session *remotehost.Session |
| 253 | remote := true |
| 254 | var err error |
| 255 | if desktop := s.remote.desktop; desktop != nil { |
| 256 | session, remote, err = desktop.acquire(requestConnection(r)) |
| 257 | } else if !s.remote.isRemote() { |
| 258 | if s.clientOnly && r.URL.Path != "/api/diagnostics/events" { |
| 259 | http.Error(w, "请先连接远程主机", 409) |
| 260 | return true |
| 261 | } |
| 262 | if id := requestConnection(r); id != "" && id != "local" { |
| 263 | http.Error(w, "连接已经切换,请重新打开当前工作台", 409) |
| 264 | return true |
| 265 | } |
| 266 | return false |
| 267 | } else { |
| 268 | session, err = s.remote.manager.Acquire(requestConnection(r)) |
| 269 | } |
| 270 | if remote && r.URL.Path == "/api/projects/client-share" { |
| 271 | http.NotFound(w, r) |
| 272 | return true |
| 273 | } |
| 274 | if remote && (r.URL.Path == "/api/environment/storage" || r.URL.Path == "/api/environment/storage/recover") { |
| 275 | http.Error(w, "请在虚拟机所在电脑上调整环境存储", http.StatusForbidden) |
| 276 | return true |
| 277 | } |
| 278 | if err != nil { |
| 279 | http.Error(w, "连接不可用或已切换,请重新选择工作环境", 409) |
| 280 | return true |
| 281 | } |
| 282 | if r.URL.Path == "/api/diagnostics/export" { |
| 283 | if !s.diagnosticMu.TryLock() { |
| 284 | http.Error(w, "正在导出另一份诊断包,请稍候", http.StatusConflict) |
| 285 | return true |
| 286 | } |
| 287 | defer s.diagnosticMu.Unlock() |
| 288 | } |
| 289 | if remote && strings.HasPrefix(r.URL.Path, "/api/mobile/") { |
| 290 | http.Error(w, "手机只连接当前电脑的 Cage 环境", http.StatusForbidden) |
| 291 | return true |
| 292 | } |
| 293 | if remote && (r.URL.Path == "/api/mobile-pair" || strings.HasPrefix(r.URL.Path, "/api/mobile-pair/")) { |
| 294 | http.Error(w, "请切换到这台电脑的本机环境,再管理手机配对", http.StatusForbidden) |
| 295 | return true |
| 296 | } |
| 297 | if remote && r.Method == "GET" && r.URL.Path == "/api/browser/files/saved" { |
| 298 | profile, err := clientDownloadProfile(s.profile, ClientContext{Mode: "remote", InstanceID: session.Ref.InstanceID}) |
| 299 | if err != nil { |
| 300 | requestError(w, err) |
| 301 | return true |
| 302 | } |
| 303 | serveSavedDownloads(w, profile) |
| 304 | return true |
| 305 | } |
| 306 | target, err := url.Parse(session.Origin) |
| 307 | if err != nil { |
| 308 | http.Error(w, "远程入口无效", 502) |
| 309 | return true |
| 310 | } |
| 311 | ctx, cancel := context.WithCancel(r.Context()) |
| 312 | stop := context.AfterFunc(session.Context, cancel) |
| 313 | defer func() { stop(); cancel() }() |
| 314 | proxy := &httputil.ReverseProxy{ |
| 315 | Transport: session.Transport, |
| 316 | FlushInterval: -1, |
| 317 | Rewrite: func(p *httputil.ProxyRequest) { |
| 318 | p.SetURL(target) |
| 319 | p.Out.Host = target.Host |
| 320 | p.Out.Header.Del(connectionHeader) |
| 321 | query := p.Out.URL.Query() |
| 322 | query.Del("connection") |
| 323 | p.Out.URL.RawQuery = query.Encode() |
| 324 | }, |
| 325 | ModifyResponse: func(response *http.Response) error { |
| 326 | response.Header.Del("Set-Cookie") |
| 327 | response.Header.Del("Content-Security-Policy") |
| 328 | response.Header.Del("Access-Control-Allow-Origin") |
| 329 | response.Header.Set("X-Content-Type-Options", "nosniff") |
| 330 | if response.StatusCode == http.StatusOK && response.Request.URL.Path == "/api/diagnostics/export" && strings.HasPrefix(response.Header.Get("Content-Type"), "application/zip") { |
| 331 | return s.addDesktopDiagnosticResponse(response) |
| 332 | } |
| 333 | if response.StatusCode >= 300 && response.StatusCode < 400 { |
| 334 | return errors.New("remote redirects are refused") |
| 335 | } |
| 336 | if downloadID := strings.TrimSuffix(strings.TrimPrefix(response.Request.URL.Path, "/api/browser/files/downloads/"), "/content"); strings.HasSuffix(response.Request.URL.Path, "/content") && browserFileID.MatchString(downloadID) { |
| 337 | name := "download" |
| 338 | _, parameters, err := mime.ParseMediaType(response.Header.Get("Content-Disposition")) |
| 339 | if err == nil && browserDownloadName(parameters["filename"]) { |
| 340 | name = parameters["filename"] |
| 341 | } |
| 342 | response.Header.Set("Content-Type", "application/octet-stream") |
| 343 | response.Header.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": name})) |
| 344 | return nil |
| 345 | } |
| 346 | if response.StatusCode != http.StatusSwitchingProtocols && response.StatusCode != http.StatusNoContent { |
| 347 | contentType, _, err := mime.ParseMediaType(response.Header.Get("Content-Type")) |
| 348 | if err != nil { |
| 349 | return errors.New("remote response has no supported content type") |
| 350 | } |
| 351 | switch contentType { |
| 352 | case "application/json", "text/plain", "text/event-stream", "application/octet-stream", "application/zip", "image/png", "image/jpeg", "image/webp": |
| 353 | default: |
| 354 | return errors.New("remote active content is refused") |
| 355 | } |
| 356 | } |
| 357 | return nil |
| 358 | }, |
| 359 | ErrorHandler: func(w http.ResponseWriter, _ *http.Request, _ error) { |
| 360 | http.Error(w, "远程连接已中断;已提交的操作请重连后核对", http.StatusBadGateway) |
| 361 | }, |
| 362 | } |
| 363 | proxy.ServeHTTP(w, r.WithContext(ctx)) |
| 364 | return true |
| 365 | } |