Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix(mars): forward typed session key to web bridge on non-baked binds (#18465)

Liang Xu84a5d30a4afe
diff --git a/__tests__/api/mars-web-bridge.test.ts b/__tests__/api/mars-web-bridge.test.ts
index f2794d5525..c31ca3c409 100644
--- a/__tests__/api/mars-web-bridge.test.ts
+++ b/__tests__/api/mars-web-bridge.test.ts
@@ -3,16 +3,32 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import {
MarsWebBridgeError,
createMarsWebBridge,
+ getMarsBridgeHeaders,
installMarsWebBridge,
probeMarsWebBridge,
} from "#/api/mars/mars-web-bridge";
+import type { Backend } from "#/api/backend-registry/types";
-const sessionApiKey = vi.hoisted(() => ({ value: null as string | null }));
-vi.mock("#/api/agent-server-config", () => ({
- getAgentServerHeaders: (): Record<string, string> =>
- sessionApiKey.value ? { "X-Session-API-Key": sessionApiKey.value } : {},
+const bakedSessionApiKey = vi.hoisted(() => ({ value: null as string | null }));
+const registeredBackends = vi.hoisted(() => ({ value: [] as Backend[] }));
+const activeLocalBackend = vi.hoisted(() => ({
+ value: null as Backend | null,
}));
+// Only the baked key is faked: `isServedOriginHost` is the real one, so the
+// tests exercise the actual origin match against the jsdom page origin.
+vi.mock("#/api/agent-server-config", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("#/api/agent-server-config")>()),
+ getBakedSessionApiKey: () => bakedSessionApiKey.value,
+}));
+
+vi.mock("#/api/backend-registry/active-store", () => ({
+ getEffectiveLocalBackend: () => activeLocalBackend.value,
+ getRegisteredBackends: () => registeredBackends.value,
+}));
+
+const PAGE_ORIGIN = window.location.origin;
+
function jsonResponse(status: number, body: unknown): Response {
return new Response(JSON.stringify(body), {
status,
@@ -23,7 +39,9 @@ function jsonResponse(status: number, body: unknown): Response {
afterEach(() => {
vi.unstubAllGlobals();
delete window.marsBridge;
- sessionApiKey.value = null;
+ bakedSessionApiKey.value = null;
+ registeredBackends.value = [];
+ activeLocalBackend.value = null;
});
describe("createMarsWebBridge", () => {
@@ -80,7 +98,7 @@ describe("createMarsWebBridge", () => {
});
it("sends the page's session key on every call so the server can admit it", async () => {
- sessionApiKey.value = "sk-page";
+ bakedSessionApiKey.value = "sk-page";
const fetchImpl = vi.fn(async () => jsonResponse(200, { result: null }));
const bridge = createMarsWebBridge(
"",
@@ -99,6 +117,131 @@ describe("createMarsWebBridge", () => {
});
});
+ it("sends the typed session key when no baked key exists on the page", async () => {
+ bakedSessionApiKey.value = null;
+ registeredBackends.value = [
+ {
+ id: "default-local",
+ name: "Local",
+ host: PAGE_ORIGIN,
+ apiKey: "qa-typed-session-key",
+ kind: "local",
+ },
+ ];
+
+ expect(getMarsBridgeHeaders()).toEqual({
+ "X-Session-API-Key": "qa-typed-session-key",
+ });
+
+ const fetchImpl = vi.fn(async () => jsonResponse(200, { result: null }));
+ const bridge = createMarsWebBridge(
+ "",
+ fetchImpl as unknown as typeof fetch,
+ );
+
+ await bridge.pauseSession("s1");
+
+ expect(fetchImpl).toHaveBeenCalledWith("/mars/rpc/pauseSession", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "X-Session-API-Key": "qa-typed-session-key",
+ },
+ body: JSON.stringify({ args: ["s1"] }),
+ });
+ });
+
+ it("prefers the active backend's key over an older one saved for the same origin", () => {
+ const current: Backend = {
+ id: "current",
+ name: "Current",
+ host: PAGE_ORIGIN,
+ apiKey: "current-key",
+ kind: "local",
+ };
+ registeredBackends.value = [
+ {
+ id: "stale",
+ name: "Stale",
+ host: PAGE_ORIGIN,
+ apiKey: "stale-key",
+ kind: "local",
+ },
+ current,
+ ];
+ activeLocalBackend.value = current;
+
+ expect(getMarsBridgeHeaders()).toEqual({
+ "X-Session-API-Key": "current-key",
+ });
+ });
+
+ it("never sends a key stored for another host, a DigitalOcean session or a cloud backend", async () => {
+ const marsSession: Backend = {
+ id: "mars-1",
+ name: "MARS Session",
+ host: `${PAGE_ORIGIN}/mars/sessions/s1`,
+ apiKey: "session-token",
+ kind: "local",
+ marsSessionId: "s1",
+ };
+ registeredBackends.value = [
+ {
+ id: "cloud-1",
+ name: "Cloud",
+ host: PAGE_ORIGIN,
+ apiKey: "cloud-key",
+ kind: "cloud",
+ },
+ {
+ id: "remote-1",
+ name: "Remote",
+ host: "https://remote.openhands.dev",
+ apiKey: "remote-key",
+ kind: "local",
+ },
+ marsSession,
+ ];
+ activeLocalBackend.value = marsSession;
+ const fetchImpl = vi.fn(async () => jsonResponse(200, { result: null }));
+ const bridge = createMarsWebBridge(
+ "",
+ fetchImpl as unknown as typeof fetch,
+ );
+
+ await bridge.pauseSession("s1");
+
+ expect(fetchImpl).toHaveBeenCalledWith("/mars/rpc/pauseSession", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ args: ["s1"] }),
+ });
+ });
+
+ it("never sends the page's key to a bridge on a foreign host", async () => {
+ bakedSessionApiKey.value = "sk-page";
+ const fetchImpl = vi.fn(async () => jsonResponse(200, { result: null }));
+ const foreignBridge = createMarsWebBridge(
+ "https://foreign-host.com",
+ fetchImpl as unknown as typeof fetch,
+ );
+
+ await foreignBridge.pauseSession("s2");
+
+ expect(fetchImpl).toHaveBeenCalledWith(
+ "https://foreign-host.com/mars/rpc/pauseSession",
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ args: ["s2"] }),
+ },
+ );
+ });
+
it("never offers OAuth", async () => {
const bridge = createMarsWebBridge("", vi.fn() as unknown as typeof fetch);
await expect(bridge.signInWithOAuth()).rejects.toBeInstanceOf(
diff --git a/src/api/mars/mars-web-bridge.ts b/src/api/mars/mars-web-bridge.ts
index fd92eb962b..2a4f01e426 100644
--- a/src/api/mars/mars-web-bridge.ts
+++ b/src/api/mars/mars-web-bridge.ts
@@ -19,7 +19,15 @@
* itself on the proxied REST calls and the WebSocket upgrade.
*/
-import { getAgentServerHeaders } from "#/api/agent-server-config";
+import {
+ getBakedSessionApiKey,
+ isServedOriginHost,
+} from "#/api/agent-server-config";
+import {
+ getEffectiveLocalBackend,
+ getRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import type { Backend } from "#/api/backend-registry/types";
import type { MarsBridge } from "./mars-tunnel-backend";
export const MARS_WEB_HEALTH_PATH = "/mars/health";
@@ -42,6 +50,50 @@ export class MarsWebBridgeError extends Error {
}
}
+/** A local backend for the page's served origin that carries a typed key. */
+function holdsServedOriginKey(backend: Backend): boolean {
+ return (
+ backend.kind === "local" &&
+ isServedOriginHost(backend.host) &&
+ backend.apiKey.trim().length > 0
+ );
+}
+
+/**
+ * Return headers required to authenticate with the Agent Canvas MARS web bridge.
+ *
+ * Attaches the session API key configured for the page's served origin:
+ * 1. Uses the baked session API key if present (e.g. default launcher).
+ * 2. Otherwise falls back to the key the user typed for the page's origin on the API key screen
+ * (stored on the local backend in the backend registry).
+ * 3. Never attaches a key if baseUrl points to a different host (foreign backend), or if
+ * the stored key belongs to a different host.
+ */
+export function getMarsBridgeHeaders(baseUrl = ""): Record<string, string> {
+ if (baseUrl && !isServedOriginHost(baseUrl)) {
+ return {};
+ }
+
+ const bakedKey = getBakedSessionApiKey();
+ if (bakedKey) {
+ return { "X-Session-API-Key": bakedKey };
+ }
+
+ // Prefer the active backend when it holds the served-origin key, so an older
+ // key saved for the same origin cannot shadow the one in use.
+ const active = getEffectiveLocalBackend();
+ const servedBackend =
+ active && holdsServedOriginKey(active)
+ ? active
+ : getRegisteredBackends().find(holdsServedOriginKey);
+
+ if (servedBackend) {
+ return { "X-Session-API-Key": servedBackend.apiKey.trim() };
+ }
+
+ return {};
+}
+
async function rpc<T>(
baseUrl: string,
method: string,
@@ -52,7 +104,7 @@ async function rpc<T>(
method: "POST",
headers: {
"Content-Type": "application/json",
- ...getAgentServerHeaders(),
+ ...getMarsBridgeHeaders(baseUrl),
},
body: JSON.stringify({ args }),
});