π OpenHands: AI-Driven Development
fix: route automation requests through cloud proxy for cloud backends (#1121)
Hiep Le0c892a51b5fd
diff --git a/__tests__/api/automation-service.test.ts b/__tests__/api/automation-service.test.tsindex 57ccbf1878..b7ccc57fa5 100644--- a/__tests__/api/automation-service.test.ts+++ b/__tests__/api/automation-service.test.ts@@ -359,6 +359,7 @@ describe("AutomationService", () => {backend: cloudBackend,method: "GET",path: "/api/automation/v1?limit=10&offset=5",+ forceProxy: true,});expect(mockGet).not.toHaveBeenCalled();expect(result).toEqual(response);@@ -373,6 +374,7 @@ describe("AutomationService", () => {backend: cloudBackend,method: "GET",path: "/api/automation/v1/abc",+ forceProxy: true,});expect(result).toEqual(mockAutomation);});@@ -386,6 +388,7 @@ describe("AutomationService", () => {backend: cloudBackend,method: "POST",path: "/api/automation/v1/abc/dispatch",+ forceProxy: true,});expect(mockPost).not.toHaveBeenCalled();expect(result).toEqual(mockRun);@@ -404,6 +407,7 @@ describe("AutomationService", () => {method: "PATCH",path: "/api/automation/v1/abc",body: { enabled: false },+ forceProxy: true,});expect(mockPatch).not.toHaveBeenCalled();expect(result).toEqual(updated);@@ -418,6 +422,7 @@ describe("AutomationService", () => {backend: cloudBackend,method: "DELETE",path: "/api/automation/v1/abc",+ forceProxy: true,});expect(mockDelete).not.toHaveBeenCalled();});@@ -440,10 +445,35 @@ describe("AutomationService", () => {backend: cloudBackend,method: "POST",path: "/api/automation/v1/abc/dispatch",+ forceProxy: true,});expect(mockPost).not.toHaveBeenCalled();expect(result).toEqual(run);});++ it("checkHealth tunnels through the cloud proxy with a fail-fast timeout and returns the upstream status", async () => {+ mockCallCloudProxy.mockResolvedValue({ status: "ok" });++ const result = await AutomationService.checkHealth();++ // Property access (vs whole-object matching) keeps these assertions+ // resilient to future additive CloudProxyRequest fields.+ const call = mockCallCloudProxy.mock.calls[0]![0];+ expect(call.method).toBe("GET");+ expect(call.path).toBe("/api/automation/health");+ expect(call.forceProxy).toBe(true);+ expect(call.timeoutSeconds).toBe(5);+ expect(mockGet).not.toHaveBeenCalled();+ expect(result).toEqual({ status: "ok" });+ });++ it("checkHealth resolves to an error status instead of throwing when the proxy call fails", async () => {+ mockCallCloudProxy.mockRejectedValue(new Error("proxy unreachable"));++ const result = await AutomationService.checkHealth();++ expect(result).toEqual({ status: "error" });+ });});// The interceptor must read the session API key from the active backenddiff --git a/__tests__/api/cloud/proxy.test.ts b/__tests__/api/cloud/proxy.test.tsindex c5f98fa137..af07f877d6 100644--- a/__tests__/api/cloud/proxy.test.ts+++ b/__tests__/api/cloud/proxy.test.ts@@ -31,12 +31,15 @@ beforeEach(() => {__resetActiveStoreForTests();vi.mocked(axios.request).mockReset();vi.mocked(axios.request).mockResolvedValue({ data: {} });+ vi.mocked(axios.post).mockReset();+ vi.mocked(axios.post).mockResolvedValue({ data: {} });});afterEach(() => {window.localStorage.clear();__resetActiveStoreForTests();vi.mocked(axios.request).mockReset();+ vi.mocked(axios.post).mockReset();});describe("callCloudProxy X-Org-Id injection", () => {@@ -95,3 +98,63 @@ describe("callCloudProxy X-Org-Id injection", () => {).not.toHaveProperty("X-Org-Id");});});++describe("callCloudProxy forceProxy routing", () => {+ it("routes through the local /api/cloud-proxy instead of the cloud host when forceProxy is set", async () => {+ // Arrange β automation endpoints opt into the proxy hop because the+ // standalone automation service's CORS allowlist rejects browser+ // requests from the local GUI origin.+ setRegisteredBackends([cloudPersonal]);+ setActiveSelection({ backendId: cloudPersonal.id, orgId: null });+ vi.mocked(axios.post).mockResolvedValue({ data: { status: "ok" } });++ // Act+ const result = await callCloudProxy({+ backend: cloudPersonal,+ method: "GET",+ path: "/api/automation/health",+ forceProxy: true,+ });++ // Assert β the browser only makes a same-origin POST to the bundled+ // agent-server's proxy endpoint carrying the upstream call as an+ // envelope, and the upstream payload is unwrapped for the caller.+ expect(axios.request).not.toHaveBeenCalled();+ const [url, envelope] = vi.mocked(axios.post).mock.calls[0]!;+ expect(url).toMatch(/\/api\/cloud-proxy$/);+ expect(envelope).toMatchObject({+ host: cloudPersonal.host,+ method: "GET",+ path: "/api/automation/health",+ });+ expect(result).toEqual({ status: "ok" });+ });++ it("carries bearer auth and X-Org-Id inside the proxy envelope", async () => {+ // Arrange β org scoping must survive the server-side hop: the envelope+ // headers are what the agent-server attaches to the upstream call in+ // place of the headers a direct browser request would have sent.+ setRegisteredBackends([cloudPersonal]);+ setActiveSelection({+ backendId: cloudPersonal.id,+ orgId: "org-personal-uuid",+ });++ // Act+ await callCloudProxy({+ backend: cloudPersonal,+ method: "GET",+ path: "/api/automation/health",+ forceProxy: true,+ });++ // Assert+ const [, envelope] = vi.mocked(axios.post).mock.calls[0]!;+ expect(+ (envelope as { headers: Record<string, string> }).headers,+ ).toMatchObject({+ Authorization: `Bearer ${cloudPersonal.apiKey}`,+ "X-Org-Id": "org-personal-uuid",+ });+ });+});diff --git a/src/api/automation-service/automation-service.api.ts b/src/api/automation-service/automation-service.api.tsindex 35496a89db..653626940d 100644--- a/src/api/automation-service/automation-service.api.ts+++ b/src/api/automation-service/automation-service.api.ts@@ -10,7 +10,7 @@ import {getEffectiveLocalBackend,} from "../backend-registry/active-store";import { NoBackendAvailableError } from "../agent-server-client-options";-import { callCloudProxy } from "../cloud/proxy";+import { callCloudProxy, type CloudProxyRequest } from "../cloud/proxy";const AUTOMATION_BASE_PATH = "/api/automation";@@ -53,6 +53,18 @@ function buildPaginationQuery(limit: number, offset: number): string {return params.toString();}+// All /api/automation/* paths are served by the standalone automation+// service, whose CORS allowlist (unlike the main cloud API's bearer-aware+// CORS) excludes the local GUI origin β so cloud calls must tunnel through+// the agent-server's /api/cloud-proxy instead of going direct from the+// browser. Funnel every cloud branch through here so a future method can't+// reintroduce the CORS failure.+function callAutomationCloudProxy<TResponse>(+ req: Omit<CloudProxyRequest, "forceProxy">,+): Promise<TResponse> {+ return callCloudProxy<TResponse>({ ...req, forceProxy: true });+}+class AutomationService {static async listAutomations(params: { limit?: number; offset?: number } = {},@@ -61,7 +73,7 @@ class AutomationService {const active = getActiveBackend().backend;if (active.kind === "cloud") {- return callCloudProxy<AutomationsResponse>({+ return callAutomationCloudProxy<AutomationsResponse>({backend: active,method: "GET",path: `${AUTOMATION_BASE_PATH}/v1?${buildPaginationQuery(limit, offset)}`,@@ -87,7 +99,7 @@ class AutomationService {const path = `${AUTOMATION_BASE_PATH}/v1/${encodeURIComponent(id)}`;if (active.kind === "cloud") {- return callCloudProxy<Automation>({+ return callAutomationCloudProxy<Automation>({backend: active,method: "GET",path,@@ -106,7 +118,7 @@ class AutomationService {const path = `${AUTOMATION_BASE_PATH}/v1/${encodeURIComponent(id)}`;if (active.kind === "cloud") {- return callCloudProxy<Automation>({+ return callAutomationCloudProxy<Automation>({backend: active,method: "PATCH",path,@@ -123,7 +135,7 @@ class AutomationService {const path = `${AUTOMATION_BASE_PATH}/v1/${encodeURIComponent(id)}`;if (active.kind === "cloud") {- await callCloudProxy<unknown>({+ await callAutomationCloudProxy<unknown>({backend: active,method: "DELETE",path,@@ -139,7 +151,7 @@ class AutomationService {const path = `${AUTOMATION_BASE_PATH}/v1/${encodeURIComponent(id)}/dispatch`;if (active.kind === "cloud") {- return callCloudProxy<AutomationRun>({+ return callAutomationCloudProxy<AutomationRun>({backend: active,method: "POST",path,@@ -159,7 +171,7 @@ class AutomationService {const basePath = `${AUTOMATION_BASE_PATH}/v1/${encodeURIComponent(id)}/runs`;if (active.kind === "cloud") {- return callCloudProxy<AutomationRunsResponse>({+ return callAutomationCloudProxy<AutomationRunsResponse>({backend: active,method: "GET",path: `${basePath}?${buildPaginationQuery(limit, offset)}`,@@ -194,7 +206,7 @@ class AutomationService {let blob: Blob;if (active.kind === "cloud") {- blob = await callCloudProxy<Blob>({+ blob = await callAutomationCloudProxy<Blob>({backend: active,method: "GET",path,@@ -221,11 +233,14 @@ class AutomationService {try {if (active.kind === "cloud") {- const response = await callCloudProxy<AutomationHealthResponse>({- backend: active,- method: "GET",- path,- });+ const response =+ await callAutomationCloudProxy<AutomationHealthResponse>({+ backend: active,+ method: "GET",+ path,+ // Fail fast, matching the local branch's 5s timeout below.+ timeoutSeconds: 5,+ });return response;}diff --git a/src/api/cloud/proxy.ts b/src/api/cloud/proxy.tsindex 3bff328bfa..9aaf22de44 100644--- a/src/api/cloud/proxy.ts+++ b/src/api/cloud/proxy.ts@@ -8,7 +8,7 @@ import { NoBackendAvailableError } from "../agent-server-client-options";import { buildAuthHeaders } from "../backend-registry/auth";import type { Backend } from "../backend-registry/types";-interface CloudProxyRequest {+export interface CloudProxyRequest {/*** Cloud backend whose bearer token authenticates the upstream call.* `backend.host` is also the default upstream host unless `hostOverride`@@ -49,6 +49,18 @@ interface CloudProxyRequest {* payload (e.g. ZIP downloads); leave undefined for default JSON.*/responseType?: "blob";+ /**+ * Force this app-host call through the bundled agent-server's+ * `/api/cloud-proxy` instead of calling the cloud host directly from the+ * browser. App-host calls normally go direct because the main cloud API+ * loosens CORS for bearer-token requests (ApiKeyAwareCORSMiddleware β+ * `Access-Control-Allow-Origin: *`). The standalone automation service+ * (`/api/automation/*`) uses a strict origin allowlist instead, so direct+ * browser requests fail CORS preflight; the same-origin proxy hop avoids+ * cross-origin entirely while attaching the same auth and `X-Org-Id`+ * headers server-side.+ */+ forceProxy?: boolean;}function buildUpstreamAuthHeaders(@@ -64,11 +76,12 @@ function buildUpstreamAuthHeaders(/*** Send a cloud request. App-host calls (`backend.host`) go directly to the- * cloud API with the cloud backend's auth headers. Runtime-sandbox calls pass- * `hostOverride`, and those still go through `/api/cloud-proxy` because the- * per-conversation runtime hosts are not the configured cloud app origin.+ * cloud API with the cloud backend's auth headers, unless `forceProxy` is+ * set. Runtime-sandbox calls pass `hostOverride`, and those still go through+ * `/api/cloud-proxy` because the per-conversation runtime hosts are not the+ * configured cloud app origin.*- * App-host auth headers are sent directly to the cloud host. Runtime auth+ * App-host auth headers are sent directly to the cloud host. Proxied auth* headers are carried in the proxy envelope and attached server-side.*/export async function callCloudProxy<TResponse = unknown>(@@ -93,7 +106,7 @@ export async function callCloudProxy<TResponse = unknown>(};const upstreamHost = req.hostOverride ?? req.backend.host;- if (!req.hostOverride) {+ if (!req.hostOverride && !req.forceProxy) {const response = await axios.request<TResponse>({url: `${upstreamHost.replace(/\/+$/, "")}${req.path}`,method: req.method,