| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "net/http" |
| 9 | "net/url" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "strings" |
| 13 | "time" |
| 14 | |
| 15 | "github.com/sylvinus/agent-vm/internal/host" |
| 16 | ) |
| 17 | |
| 18 | |
| 19 | |
| 20 | type AgentTarget struct { |
| 21 | Scope string `json:"scope"` |
| 22 | Connection string `json:"connection_id,omitempty"` |
| 23 | } |
| 24 | |
| 25 | func agentConnectTarget(ctx context.Context, configPath string, target AgentTarget) (*controllerClient, error) { |
| 26 | if target.Scope == "" || target.Scope == "local" { |
| 27 | return agentConnect(ctx, configPath) |
| 28 | } |
| 29 | if target.Scope != "desktop" && target.Scope != "selected" && target.Scope != "client" { |
| 30 | return nil, &AgentError{Code: "invalid_input", Message: "scope must be local, desktop, selected or client.", NextAction: "capabilities"} |
| 31 | } |
| 32 | if target.Scope == "selected" && target.Connection == "" { |
| 33 | return nil, &AgentError{Code: "invalid_input", Message: "selected scope requires --connection from client.context.", NextAction: "client.context"} |
| 34 | } |
| 35 | path := desktopConfigPath(configPath) |
| 36 | if target.Scope == "client" { |
| 37 | path = configPath |
| 38 | } |
| 39 | c, err := connectController(filepath.Dir(path)) |
| 40 | if err != nil { |
| 41 | return nil, &AgentError{Code: "service_unavailable", Message: "Open the Cage desktop before managing client configuration.", NextAction: "open_desktop"} |
| 42 | } |
| 43 | want, err := currentController() |
| 44 | if err != nil || !want.matches(c.launch.Controller) || (target.Scope != "client" && !c.launch.DesktopGateway) || (target.Scope == "client" && !c.launch.ClientOnly) || filepath.Clean(c.launch.ConfigPath) != filepath.Clean(path) { |
| 45 | c.close() |
| 46 | return nil, &AgentError{Code: "controller_mismatch", Message: "The desktop controller does not match this CLI and configuration.", NextAction: "open_desktop"} |
| 47 | } |
| 48 | u, _ := url.Parse(c.launch.URL) |
| 49 | code, err := c.callContext(ctx, "POST", "/api/session", map[string]string{"token": u.Fragment}, nil) |
| 50 | if err != nil || code != 200 { |
| 51 | c.close() |
| 52 | return nil, agentHTTPError(401) |
| 53 | } |
| 54 | c.client.Jar.SetCookies(u, []*http.Cookie{{Name: cookieName + "_" + u.Port() + "-desktop", Value: trustedViewProof(c.record.Token), Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode}}) |
| 55 | return c, nil |
| 56 | } |
| 57 | |
| 58 | type AgentResponse struct { |
| 59 | HTTPStatus int `json:"http_status"` |
| 60 | ContentType string `json:"content_type,omitempty"` |
| 61 | Recovery string `json:"recovery,omitempty"` |
| 62 | Data json.RawMessage `json:"body,omitempty"` |
| 63 | Path string `json:"path,omitempty"` |
| 64 | } |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | func AgentRequest(ctx context.Context, configPath string, target AgentTarget, method, path string, input io.Reader, contentType, output string) (AgentResponse, error) { |
| 71 | var result AgentResponse |
| 72 | u, err := url.Parse(path) |
| 73 | if err != nil || u.IsAbs() || u.Host != "" || !strings.HasPrefix(u.Path, "/api/") || u.Fragment != "" || strings.ContainsAny(path, "\r\n\\") || strings.Contains(u.Path, "//") || strings.Contains(u.Path, "/../") { |
| 74 | return result, &AgentError{Code: "invalid_input", Message: "Use a relative /api/ path without a host, fragment or traversal.", NextAction: "capabilities"} |
| 75 | } |
| 76 | switch method { |
| 77 | case "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD": |
| 78 | default: |
| 79 | return result, &AgentError{Code: "invalid_input", Message: "Unsupported HTTP method.", NextAction: "capabilities"} |
| 80 | } |
| 81 | |
| 82 | |
| 83 | |
| 84 | if u.Path == "/api/agent/native/window" || u.Path == "/api/account/device-enroll" || u.Path == "/api/account/device-unlock" || u.Path == "/api/account/device-revoke" || u.Path == "/api/session" || u.Path == "/api/launch" || u.Path == "/api/handoff" || u.Path == "/api/desktop-owner" || strings.HasPrefix(u.Path, "/api/desktop-local/") { |
| 85 | return result, &AgentError{Code: "native_transport_required", Message: "Use native.submit with the same accountDevice or desktop action. Transport credentials are not exported.", NextAction: "native.submit"} |
| 86 | } |
| 87 | |
| 88 | |
| 89 | clientPath := strings.HasPrefix(u.Path, "/api/client/") || strings.HasPrefix(u.Path, "/api/agent/native") || u.Path == "/api/agent/routes" |
| 90 | if target.Scope == "client" && !clientPath && target.Connection == "" { |
| 91 | return result, &AgentError{Code: "invalid_input", Message: "Client workload requests require the explicit selected --connection", NextAction: "client.context"} |
| 92 | } |
| 93 | if target.Scope == "desktop" && !clientPath { |
| 94 | return result, &AgentError{Code: "invalid_input", Message: "Use selected scope with --connection for workload requests through the desktop.", NextAction: "client.context"} |
| 95 | } |
| 96 | if output != "" { |
| 97 | if !filepath.IsAbs(output) { |
| 98 | return result, &AgentError{Code: "invalid_input", Message: "output must be an absolute new file path", NextAction: "capabilities"} |
| 99 | } |
| 100 | if _, err := os.Lstat(output); !os.IsNotExist(err) { |
| 101 | return result, &AgentError{Code: "invalid_input", Message: "Existing output files are preserved", NextAction: "capabilities"} |
| 102 | } |
| 103 | } |
| 104 | c, err := agentConnectTarget(ctx, configPath, target) |
| 105 | if err != nil { |
| 106 | return result, err |
| 107 | } |
| 108 | defer c.close() |
| 109 | c.client.Timeout = 2 * time.Minute |
| 110 | req, err := http.NewRequestWithContext(ctx, method, c.origin+path, input) |
| 111 | if err != nil { |
| 112 | return result, err |
| 113 | } |
| 114 | req.Header.Set("Origin", c.origin) |
| 115 | if contentType != "" { |
| 116 | req.Header.Set("Content-Type", contentType) |
| 117 | } |
| 118 | connection := "local" |
| 119 | if target.Connection != "" { |
| 120 | connection = target.Connection |
| 121 | } |
| 122 | req.Header.Set(connectionHeader, connection) |
| 123 | response, err := c.client.Do(req) |
| 124 | if err != nil { |
| 125 | return result, &AgentError{Code: "outcome_unknown", Message: "The request was interrupted. Inspect the original target before repeating a mutation.", NextAction: "status"} |
| 126 | } |
| 127 | defer response.Body.Close() |
| 128 | result.HTTPStatus = response.StatusCode |
| 129 | result.ContentType = response.Header.Get("Content-Type") |
| 130 | result.Recovery = response.Header.Get("X-Cage-Recovery") |
| 131 | if response.StatusCode < 200 || response.StatusCode >= 300 { |
| 132 | body, _ := io.ReadAll(io.LimitReader(response.Body, 64<<10)) |
| 133 | e := agentHTTPError(response.StatusCode) |
| 134 | e.Message += " " + agentRedact(strings.TrimSpace(string(body))) |
| 135 | return result, e |
| 136 | } |
| 137 | if output != "" { |
| 138 | if !filepath.IsAbs(output) { |
| 139 | return result, &AgentError{Code: "invalid_input", Message: "output must be an absolute new file path.", NextAction: "capabilities"} |
| 140 | } |
| 141 | f, err := os.CreateTemp(filepath.Dir(output), ".cage-agent-response-*") |
| 142 | if err != nil { |
| 143 | return result, err |
| 144 | } |
| 145 | defer os.Remove(f.Name()) |
| 146 | if err := host.ProtectFile(f.Name()); err != nil { |
| 147 | f.Close() |
| 148 | return result, err |
| 149 | } |
| 150 | _, copyErr := io.Copy(f, response.Body) |
| 151 | err = errors.Join(copyErr, f.Sync(), f.Close()) |
| 152 | if err != nil { |
| 153 | return result, err |
| 154 | } |
| 155 | if err = os.Link(f.Name(), output); err != nil { |
| 156 | return result, err |
| 157 | } |
| 158 | result.Path = output |
| 159 | return result, nil |
| 160 | } |
| 161 | if response.StatusCode == 204 || method == "HEAD" { |
| 162 | return result, nil |
| 163 | } |
| 164 | data, err := io.ReadAll(io.LimitReader(response.Body, (32<<20)+1)) |
| 165 | if err != nil || len(data) > 32<<20 { |
| 166 | return result, &AgentError{Code: "invalid_response", Message: "Response exceeds 32 MiB or was interrupted; use --output for a file response.", NextAction: "status"} |
| 167 | } |
| 168 | if !json.Valid(data) { |
| 169 | return result, &AgentError{Code: "output_required", Message: "This response is not JSON. Use --output with a new absolute file path for binary or streaming content.", NextAction: "capabilities"} |
| 170 | } |
| 171 | result.Data = data |
| 172 | return result, nil |
| 173 | } |
| 174 | |
| 175 | func AgentCallTarget(ctx context.Context, configPath string, target AgentTarget, operation string, input json.RawMessage) (json.RawMessage, error) { |
| 176 | for _, op := range AgentOperations() { |
| 177 | if op.Name == operation { |
| 178 | if err := agentValidateInput(input, op.InputSchema); err != nil { |
| 179 | return nil, err |
| 180 | } |
| 181 | if len(input) == 0 { |
| 182 | input = json.RawMessage(`{}`) |
| 183 | } |
| 184 | result, err := AgentRequest(ctx, configPath, target, op.method, op.path, strings.NewReader(string(input)), "application/json", "") |
| 185 | return result.Data, err |
| 186 | } |
| 187 | } |
| 188 | return nil, &AgentError{Code: "unknown_operation", Message: "Unknown operation. Read capabilities or use request for an existing UI endpoint.", NextAction: "capabilities"} |
| 189 | } |