π OpenHands: AI-Driven Development
fix(security): authenticate WebSockets outside URLs (#16095)
simonrosenbergbab6484f85db
diff --git a/__tests__/contexts/conversation-websocket-context.test.tsx b/__tests__/contexts/conversation-websocket-context.test.tsxindex 1dcc4502fb..bcc05328e7 100644--- a/__tests__/contexts/conversation-websocket-context.test.tsx+++ b/__tests__/contexts/conversation-websocket-context.test.tsx@@ -14,30 +14,43 @@ import {getStoredConversationMetadata,setStoredConversationMetadata,} from "#/api/conversation-metadata-store";+import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";import type { MessageEvent } from "#/types/agent-server/core";-// Captures the main socket's `onMessage` (`handleMainMessage`) so tests can-// drive the live message path without a real WebSocket. Only the main socket-// gets a non-empty url (planning stays ""), so url presence discriminates it.+type CapturedWebSocketOptions = {+ onMessage?: (event: { data: string }) => void;+ queryParams?: Record<string, string | boolean>;+ sessionApiKey?: string | null;+};+const wsCapture = vi.hoisted(() => ({mainOnMessage: null as null | ((event: { data: string }) => void),+ mainOptions: null as CapturedWebSocketOptions | null,+ calls: [] as Array<{+ url: string;+ options?: CapturedWebSocketOptions;+ }>,}));// Keep the units under test real (the provider, `useConversationHistory`, the// event store). Only the network is stubbed: the WebSocket transport and the// REST service the history query depends on.vi.mock("#/hooks/use-websocket", () => ({- useWebSocket: vi.fn(- (- url: string,- options?: { onMessage?: (event: { data: string }) => void },- ) => {- if (url && options?.onMessage) {- wsCapture.mainOnMessage = options.onMessage;- }- return { socket: null, reconnect: vi.fn() };- },- ),+ useWebSocket: vi.fn((url: string, options?: CapturedWebSocketOptions) => {+ if (url) {+ wsCapture.calls.push({ url, options });+ }+ if (+ url &&+ options?.onMessage &&+ options.queryParams &&+ "resend_mode" in options.queryParams+ ) {+ wsCapture.mainOnMessage = options.onMessage;+ wsCapture.mainOptions = options;+ }+ return { socket: null, reconnect: vi.fn() };+ }),}));vi.mock("#/hooks/query/use-user-conversation", () => ({useUserConversation: vi.fn(),@@ -76,6 +89,8 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()beforeEach(() => {wsCapture.mainOnMessage = null;+ wsCapture.mainOptions = null;+ wsCapture.calls.length = 0;window.localStorage.clear();queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },@@ -160,6 +175,89 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ());});+ it("keeps the session key out of WebSocket query parameters", async () => {+ const sessionApiKey = `sk-oh-${"c".repeat(64)}`;++ render(+ <QueryClientProvider client={queryClient}>+ <ConversationWebSocketProvider+ conversationId="conv-auth"+ conversationUrl="http://localhost/api"+ sessionApiKey={sessionApiKey}+ >+ <div />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );++ await waitFor(() => expect(wsCapture.mainOptions).not.toBeNull());++ expect(wsCapture.mainOptions?.sessionApiKey).toBe(sessionApiKey);+ expect(wsCapture.mainOptions?.queryParams).not.toHaveProperty(+ "session_api_key",+ );+ });++ it("uses the planning sub-conversation session key", async () => {+ const mainSessionApiKey = `sk-oh-main-${"m".repeat(48)}`;+ const planningSessionApiKey = `sk-oh-plan-${"p".repeat(48)}`;+ const planningConversation: AppConversation = {+ id: "planning-auth",+ created_by_user_id: null,+ selected_repository: null,+ selected_branch: null,+ git_provider: null,+ title: "Planner",+ trigger: null,+ pr_number: [],+ llm_model: null,+ metrics: null,+ created_at: "2026-07-28T00:00:00Z",+ updated_at: "2026-07-28T00:00:00Z",+ execution_status: null,+ conversation_url:+ "http://planner.example/api/conversations/planning-auth",+ session_api_key: planningSessionApiKey,+ sandbox_id: null,+ sub_conversation_ids: [],+ };++ render(+ <QueryClientProvider client={queryClient}>+ <ConversationWebSocketProvider+ conversationId="conv-auth"+ conversationUrl="http://main.example/api/conversations/conv-auth"+ sessionApiKey={mainSessionApiKey}+ subConversationIds={[planningConversation.id]}+ subConversations={[planningConversation]}+ >+ <div />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );++ await waitFor(() =>+ expect(+ wsCapture.calls.some(({ url }) =>+ url.endsWith("/sockets/events/planning-auth"),+ ),+ ).toBe(true),+ );++ const planningCall = wsCapture.calls.find(({ url }) =>+ url.endsWith("/sockets/events/planning-auth"),+ );++ expect(planningCall?.url).toBe(+ "ws://planner.example/sockets/events/planning-auth",+ );+ expect(planningCall?.options?.sessionApiKey).toBe(planningSessionApiKey);+ expect(planningCall?.options?.queryParams).toEqual({ resend_all: true });+ expect(planningCall?.options?.queryParams).not.toHaveProperty(+ "session_api_key",+ );+ });+it("preserves the conversation's attached plugins across an agent-triggered model switch", async () => {// Arrange: the conversation's metadata already carries an attached plugin.setStoredConversationMetadata("conv-switch", {diff --git a/__tests__/hooks/use-bash-command-runner.test.ts b/__tests__/hooks/use-bash-command-runner.test.tsnew file mode 100644index 0000000000..8f9b86c772--- /dev/null+++ b/__tests__/hooks/use-bash-command-runner.test.ts@@ -0,0 +1,134 @@+import { renderHook } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { useBashCommandRunner } from "#/hooks/use-bash-command-runner";++class MockWebSocket {+ static readonly CONNECTING = 0;+ static readonly OPEN = 1;+ static readonly CLOSING = 2;+ static readonly CLOSED = 3;+ static instance: MockWebSocket | null = null;++ readonly url: string;+ readonly sent: string[] = [];+ readyState = MockWebSocket.CONNECTING;+ onopen: (() => void) | null = null;+ onmessage: ((event: MessageEvent) => void) | null = null;+ onclose: (() => void) | null = null;+ onerror: (() => void) | null = null;++ constructor(url: string) {+ this.url = url;+ MockWebSocket.instance = this;+ }++ send(data: string) {+ if (this.readyState !== MockWebSocket.OPEN) {+ throw new DOMException("WebSocket is not open", "InvalidStateError");+ }+ this.sent.push(data);+ }++ open() {+ this.readyState = MockWebSocket.OPEN;+ this.onopen?.();+ }++ receive(data: unknown) {+ this.onmessage?.(+ new MessageEvent("message", { data: JSON.stringify(data) }),+ );+ }++ close() {+ this.readyState = MockWebSocket.CLOSED;+ }+}++describe("useBashCommandRunner", () => {+ afterEach(() => {+ MockWebSocket.instance = null;+ vi.unstubAllGlobals();+ });++ it("sends auth before queued commands without putting the key in the URL", async () => {+ vi.stubGlobal("WebSocket", MockWebSocket);+ const sessionApiKey = `sk-oh-${"b".repeat(64)}`;+ const { result, unmount } = renderHook(() =>+ useBashCommandRunner(+ "https://runtime.example.com/api/conversations/conv-1",+ sessionApiKey,+ true,+ ),+ );+ const socket = MockWebSocket.instance!;+ socket.readyState = MockWebSocket.OPEN;++ const command = result.current("pwd", "/workspace", 30);++ expect(socket.sent).toEqual([]);+ socket.open();++ expect(socket.url).not.toContain(sessionApiKey);+ expect(socket.url).not.toContain("session_api_key");+ expect(socket.sent).toEqual([+ JSON.stringify({ type: "auth", session_api_key: sessionApiKey }),+ JSON.stringify({ command: "pwd", cwd: "/workspace", timeout: 30 }),+ ]);++ socket.receive({ kind: "BashCommand", id: "command-1" });+ socket.receive({+ kind: "BashOutput",+ command_id: "command-1",+ stdout: "/workspace\n",+ stderr: "",+ exit_code: 0,+ });+ await expect(command).resolves.toEqual({+ exit_code: 0,+ stdout: "/workspace\n",+ stderr: "",+ });++ unmount();+ });++ it("sends queued commands without an auth frame when no key is configured", async () => {+ vi.stubGlobal("WebSocket", MockWebSocket);+ const { result, unmount } = renderHook(() =>+ useBashCommandRunner(+ "http://runtime.example.com/api/conversations/conv-1",+ null,+ true,+ ),+ );+ const socket = MockWebSocket.instance!;+ const command = result.current("git status", "/workspace", 10);++ expect(socket.sent).toEqual([]);+ socket.open();+ expect(socket.sent).toEqual([+ JSON.stringify({+ command: "git status",+ cwd: "/workspace",+ timeout: 10,+ }),+ ]);++ socket.receive({ kind: "BashCommand", id: "command-1" });+ socket.receive({+ kind: "BashOutput",+ command_id: "command-1",+ stdout: "",+ stderr: "",+ exit_code: 0,+ });+ await expect(command).resolves.toEqual({+ exit_code: 0,+ stdout: "",+ stderr: "",+ });++ unmount();+ });+});diff --git a/__tests__/hooks/use-websocket.test.ts b/__tests__/hooks/use-websocket.test.tsindex 899083f878..3f2f4a0de0 100644--- a/__tests__/hooks/use-websocket.test.ts+++ b/__tests__/hooks/use-websocket.test.ts@@ -298,6 +298,86 @@ describe("useWebSocket", () => {}});+ it("should send the session key before application messages on every connection", async () => {+ class MockWebSocket {+ static readonly CONNECTING = 0;+ static readonly OPEN = 1;+ static readonly CLOSING = 2;+ static readonly CLOSED = 3;+ static instance: MockWebSocket | null = null;+ static readonly instances: MockWebSocket[] = [];++ readonly url: string;+ readonly sent: string[] = [];+ readyState = MockWebSocket.CONNECTING;+ onopen: ((event: Event) => void) | null = null;+ onmessage: ((event: MessageEvent) => void) | null = null;+ onclose: ((event: CloseEvent) => void) | null = null;+ onerror: ((event: Event) => void) | null = null;++ constructor(url: string) {+ this.url = url;+ MockWebSocket.instance = this;+ MockWebSocket.instances.push(this);+ queueMicrotask(() => {+ this.readyState = MockWebSocket.OPEN;+ this.onopen?.(new Event("open"));+ });+ }++ send(data: string) {+ if (this.readyState !== MockWebSocket.OPEN) {+ throw new DOMException("WebSocket is not open", "InvalidStateError");+ }+ this.sent.push(data);+ }++ close() {+ this.readyState = MockWebSocket.CLOSED;+ }+ }++ const originalWebSocket = globalThis.WebSocket;+ vi.stubGlobal("WebSocket", MockWebSocket);+ const sessionApiKey = `sk-oh-${"a".repeat(64)}`;+ const expectedFrames = [+ JSON.stringify({ type: "auth", session_api_key: sessionApiKey }),+ "application-message",+ ];++ try {+ const { result, unmount } = renderHook(() =>+ useWebSocket("ws://acme.com/ws", {+ sessionApiKey,+ onOpen: () => MockWebSocket.instance?.send("application-message"),+ }),+ );+ const firstSocket = MockWebSocket.instance!;++ expect(firstSocket.readyState).toBe(MockWebSocket.CONNECTING);+ expect(firstSocket.sent).toEqual([]);+ await waitForConnection(result);++ expect(firstSocket.url).toBe("ws://acme.com/ws");+ expect(firstSocket.sent).toEqual(expectedFrames);++ act(() => {+ result.current.reconnect();+ });++ await waitFor(() => {+ expect(MockWebSocket.instances).toHaveLength(2);+ expect(MockWebSocket.instances[1].sent).toEqual(expectedFrames);+ });++ unmount();+ } finally {+ globalThis.WebSocket = originalWebSocket;+ MockWebSocket.instance = null;+ MockWebSocket.instances.length = 0;+ }+ });+// Skipped: flaky in CI - see comment at top of fileit.skip("should call onOpen handler when WebSocket connection opens", async () => {const onOpenSpy = vi.fn();diff --git a/src/contexts/conversation-websocket-context.tsx b/src/contexts/conversation-websocket-context.tsxindex 483867eb00..f21aa89ccd 100644--- a/src/contexts/conversation-websocket-context.tsx+++ b/src/contexts/conversation-websocket-context.tsx@@ -863,13 +863,9 @@ export function ConversationWebSocketProvider({? { resend_mode: "since", after_timestamp: initialAfterTimestamp }: { resend_mode: "all" };- // Add session_api_key if available- if (sessionApiKey) {- queryParams.session_api_key = sessionApiKey;- }-return {queryParams,+ sessionApiKey,reconnect: { enabled: true },onOpen: () => {setMainConnectionState("OPEN");@@ -902,15 +898,13 @@ export function ConversationWebSocketProvider({resend_all: true,};- // Add session_api_key if available- if (sessionApiKey) {- queryParams.session_api_key = sessionApiKey;- }-const planningAgentConversation = subConversations?.[0];+ const planningApiKey =+ planningAgentConversation?.session_api_key ?? sessionApiKey;return {queryParams,+ sessionApiKey: planningApiKey,reconnect: { enabled: true },onOpen: async () => {setPlanningConnectionState("OPEN");diff --git a/src/hooks/use-bash-command-runner.ts b/src/hooks/use-bash-command-runner.tsindex dd57dbd8d9..2167c834f2 100644--- a/src/hooks/use-bash-command-runner.ts+++ b/src/hooks/use-bash-command-runner.ts@@ -6,6 +6,7 @@ import type {BashOutput,} from "@openhands/typescript-client";import type { CommandResult } from "#/api/runtime-service/agent-server-runtime-service";+import { sendWebSocketAuth } from "#/utils/websocket-auth";import { buildBashWebSocketUrl } from "#/utils/websocket-url";interface WaitingCommand {@@ -54,8 +55,7 @@ function isBashError(event: BashEvent): event is BashError {* received from the server is paired with the oldest outstanding request in* the queue, and subsequent `BashOutput` events are matched by `command_id`.*- * Commands queued while the socket is still in the CONNECTING state are- * buffered and flushed automatically when the socket opens.+ * Commands are buffered until the socket's open handler sends authentication.*/export function useBashCommandRunner(conversationUrl: string | null | undefined,@@ -63,8 +63,8 @@ export function useBashCommandRunner(enabled: boolean,): BashCommandRunner {const wsRef = useRef<WebSocket | null>(null);- // Commands waiting for the socket to transition from CONNECTING β OPEN- const connectingQueueRef = useRef<WaitingCommand[]>([]);+ const readyWsRef = useRef<WebSocket | null>(null);+ const waitingQueueRef = useRef<WaitingCommand[]>([]);// Commands whose request was sent; waiting for the BashCommand echo to get command_idconst pendingQueueRef = useRef<PendingCommand[]>([]);// Commands whose command_id is known; waiting for BashOutput with non-null exit_code@@ -73,23 +73,25 @@ export function useBashCommandRunner(useEffect(() => {if (!enabled) return;- const wsUrl = buildBashWebSocketUrl(conversationUrl, sessionApiKey);+ const wsUrl = buildBashWebSocketUrl(conversationUrl);const ws = new WebSocket(wsUrl);wsRef.current = ws;+ readyWsRef.current = null;ws.onopen = () => {- // Flush any commands that arrived while connecting+ sendWebSocketAuth(ws, sessionApiKey);+ readyWsRef.current = ws;for (const {command,cwd,timeout,resolve,reject,- } of connectingQueueRef.current) {+ } of waitingQueueRef.current) {pendingQueueRef.current.push({ resolve, reject });ws.send(JSON.stringify({ command, cwd, timeout }));}- connectingQueueRef.current = [];+ waitingQueueRef.current = [];};ws.onmessage = (event: MessageEvent) => {@@ -131,8 +133,8 @@ export function useBashCommandRunner(function rejectAll(reason: string): void {const err = new Error(reason);- for (const { reject: rej } of connectingQueueRef.current) rej(err);- connectingQueueRef.current = [];+ for (const { reject: rej } of waitingQueueRef.current) rej(err);+ waitingQueueRef.current = [];for (const p of pendingQueueRef.current) p.reject(err);pendingQueueRef.current = [];for (const a of activeCommandsRef.current.values()) a.reject(err);@@ -141,11 +143,13 @@ export function useBashCommandRunner(ws.onclose = () => {wsRef.current = null;+ readyWsRef.current = null;rejectAll("Bash WebSocket closed");};ws.onerror = () => {wsRef.current = null;+ readyWsRef.current = null;rejectAll("Bash WebSocket error");};@@ -155,6 +159,7 @@ export function useBashCommandRunner(ws.onerror = null;ws.close();wsRef.current = null;+ readyWsRef.current = null;rejectAll("Bash WebSocket unmounted");};}, [enabled, conversationUrl, sessionApiKey]);@@ -171,8 +176,8 @@ export function useBashCommandRunner(reject(new Error("Bash WebSocket not available"));return;}- if (ws.readyState === WebSocket.CONNECTING) {- connectingQueueRef.current.push({+ if (ws.readyState !== WebSocket.OPEN || readyWsRef.current !== ws) {+ waitingQueueRef.current.push({command,cwd,timeout,diff --git a/src/hooks/use-websocket.ts b/src/hooks/use-websocket.tsindex 9c603f9330..dd63a5f530 100644--- a/src/hooks/use-websocket.ts+++ b/src/hooks/use-websocket.ts@@ -1,7 +1,9 @@import React from "react";+import { sendWebSocketAuth } from "#/utils/websocket-auth";export interface WebSocketHookOptions {queryParams?: Record<string, string | boolean>;+ sessionApiKey?: string | null;onOpen?: (event: Event) => void;onClose?: (event: CloseEvent) => void;onMessage?: (event: MessageEvent) => void;@@ -56,6 +58,7 @@ export const useWebSocket = <T = string>(allowedToReconnectRef.current.add(ws);ws.onopen = (event) => {+ sendWebSocketAuth(ws, optionsRef.current?.sessionApiKey);setIsConnected(true);setError(null); // Clear any previous errorssetIsReconnecting(false);diff --git a/src/utils/websocket-auth.ts b/src/utils/websocket-auth.tsnew file mode 100644index 0000000000..6404cc36be--- /dev/null+++ b/src/utils/websocket-auth.ts@@ -0,0 +1,18 @@+const WEBSOCKET_AUTH_TYPE = "auth";+const WEBSOCKET_SESSION_KEY_FIELD = "session_api_key";++export function sendWebSocketAuth(+ socket: Pick<WebSocket, "send">,+ sessionApiKey: string | null | undefined,+): void {+ if (!sessionApiKey) {+ return;+ }++ socket.send(+ JSON.stringify({+ type: WEBSOCKET_AUTH_TYPE,+ [WEBSOCKET_SESSION_KEY_FIELD]: sessionApiKey,+ }),+ );+}diff --git a/src/utils/websocket-url.ts b/src/utils/websocket-url.tsindex 38d11362ba..2f060900c6 100644--- a/src/utils/websocket-url.ts+++ b/src/utils/websocket-url.ts@@ -84,12 +84,10 @@ function getConversationUrlProtocol(* events socket so it works in both direct-connect and reverse-proxy deployments.** @param conversationUrl The conversation URL containing host/port- * @param sessionApiKey Optional session API key (appended as query param)* @returns WebSocket URL for the bash-events endpoint*/export function buildBashWebSocketUrl(conversationUrl: string | null | undefined,- sessionApiKey?: string | null,): string {const baseHost = extractBaseHost(conversationUrl);const pathPrefix = extractPathPrefix(conversationUrl);@@ -99,11 +97,7 @@ export function buildBashWebSocketUrl(getConversationUrlProtocol(conversationUrl) === "https:";const protocol = pageIsSecure || targetIsSecure ? "wss:" : "ws:";- const base = `${protocol}//${baseHost}${pathPrefix}/sockets/bash-events`;- if (sessionApiKey) {- return `${base}?session_api_key=${encodeURIComponent(sessionApiKey)}`;- }- return base;+ return `${protocol}//${baseHost}${pathPrefix}/sockets/bash-events`;}/**