Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: add cross-origin authentication token handling for WebSocket URLs (#9077)

Myles Scolnick3924c127f2ad
diff --git a/frontend/src/core/runtime/__tests__/runtime.test.ts b/frontend/src/core/runtime/__tests__/runtime.test.ts
index a5aae8fd6b..c0a9a9f009 100644
--- a/frontend/src/core/runtime/__tests__/runtime.test.ts
+++ b/frontend/src/core/runtime/__tests__/runtime.test.ts
@@ -86,6 +86,74 @@ describe("RuntimeManager", () => {
});
});
+ describe("cross-origin auth token in WS URLs", () => {
+ it("should add access_token to WS URL when cross-origin with authToken", () => {
+ // example.com is cross-origin relative to the test environment (localhost)
+ const runtime = new RuntimeManager(
+ {
+ url: "https://sandbox.example.com",
+ lazy: true,
+ authToken: "my-secret-token",
+ },
+ true,
+ );
+ const url = runtime.getWsURL("s_123" as SessionId);
+
+ expect(url.searchParams.get("access_token")).toBe("my-secret-token");
+ expect(url.searchParams.get("session_id")).toBe("s_123");
+ });
+
+ it("should not add access_token to WS URL when same-origin", () => {
+ const runtime = new RuntimeManager(
+ {
+ url: window.location.origin,
+ lazy: true,
+ authToken: "my-secret-token",
+ },
+ true,
+ );
+ const url = runtime.getWsURL("s_123" as SessionId);
+
+ expect(url.searchParams.get("access_token")).toBeNull();
+ });
+
+ it("should not add access_token when no authToken is configured", () => {
+ const runtime = new RuntimeManager(
+ {
+ url: "https://sandbox.example.com",
+ lazy: true,
+ },
+ true,
+ );
+ const url = runtime.getWsURL("s_123" as SessionId);
+
+ expect(url.searchParams.get("access_token")).toBeNull();
+ });
+
+ it("should add access_token to all WS URL types when cross-origin", () => {
+ const runtime = new RuntimeManager(
+ {
+ url: "https://sandbox.example.com",
+ lazy: true,
+ authToken: "my-secret-token",
+ },
+ true,
+ );
+
+ const wsUrl = runtime.getWsURL("s_123" as SessionId);
+ const wsSyncUrl = runtime.getWsSyncURL("s_123" as SessionId);
+ const terminalUrl = runtime.getTerminalWsURL();
+
+ expect(wsUrl.searchParams.get("access_token")).toBe("my-secret-token");
+ expect(wsSyncUrl.searchParams.get("access_token")).toBe(
+ "my-secret-token",
+ );
+ expect(terminalUrl.searchParams.get("access_token")).toBe(
+ "my-secret-token",
+ );
+ });
+ });
+
describe("getWsSyncURL", () => {
it("should return WebSocket Sync URL", () => {
const runtime = new RuntimeManager(mockConfig);
@@ -117,12 +185,52 @@ describe("RuntimeManager", () => {
expect(url.pathname).toBe("/lsp/pylsp");
});
- it("should return copilot URL", () => {
- const runtime = new RuntimeManager(mockConfig);
+ it("should return copilot URL without non-auth query params", () => {
+ const runtime = new RuntimeManager({
+ url: "https://example.com?foo=bar&baz=qux",
+ lazy: true,
+ });
const url = runtime.getLSPURL("copilot");
expect(url.protocol).toBe("wss:");
expect(url.pathname).toBe("/lsp/copilot");
+ expect(url.searchParams.get("foo")).toBeNull();
+ expect(url.searchParams.get("baz")).toBeNull();
+ });
+
+ it("should preserve access_token on copilot URL when cross-origin", () => {
+ const runtime = new RuntimeManager(
+ {
+ url: "https://sandbox.example.com?foo=bar",
+ lazy: true,
+ authToken: "my-secret-token",
+ },
+ true,
+ );
+ const url = runtime.getLSPURL("copilot");
+
+ expect(url.protocol).toBe("wss:");
+ expect(url.pathname).toBe("/lsp/copilot");
+ expect(url.searchParams.get("access_token")).toBe("my-secret-token");
+ // Other params should be stripped
+ expect(url.searchParams.get("foo")).toBeNull();
+ });
+
+ it("should not have access_token on copilot URL when same-origin", () => {
+ const runtime = new RuntimeManager(
+ {
+ url: window.location.origin,
+ lazy: true,
+ authToken: "my-secret-token",
+ },
+ true,
+ );
+ const url = runtime.getLSPURL("copilot");
+
+ expect(url.protocol).toBe("ws:");
+ expect(url.pathname).toBe("/lsp/copilot");
+ expect(url.searchParams.get("access_token")).toBeNull();
+ expect(url.search).toBe("");
});
});
@@ -200,6 +308,34 @@ describe("RuntimeManager", () => {
expect(result).toBe(false);
});
+
+ it("should update config.url on redirect, stripping /health from pathname", async () => {
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ redirected: true,
+ url: "https://sandbox.example.com/health?some_value=abc123",
+ });
+
+ const runtime = new RuntimeManager(
+ {
+ ...mockConfig,
+ url: "https://backend.example.com/lazy?some_value=abc123",
+ },
+ true, // lazy — don't call init() in constructor
+ );
+ const result = await runtime.isHealthy();
+
+ expect(result).toBe(true);
+ // Should strip /health from pathname but preserve query params
+ const wsUrl = runtime.getWsURL("s_test" as SessionId);
+ expect(wsUrl.pathname).toBe("/ws");
+ expect(wsUrl.hostname).toBe("sandbox.example.com");
+ expect(wsUrl.searchParams.get("some_value")).toBe("abc123");
+
+ // Clean up side effects
+ document.querySelectorAll("base").forEach((el) => el.remove());
+ global.fetch = vi.fn().mockResolvedValue({ ok: false });
+ });
});
describe("waitForHealthy", () => {
diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.ts
index 9132dd6827..24bcc8fe71 100644
--- a/frontend/src/core/runtime/runtime.ts
+++ b/frontend/src/core/runtime/runtime.ts
@@ -88,6 +88,15 @@ export class RuntimeManager {
searchParams,
/* restrictToKnownQueryParams =*/ false,
);
+
+ // For cross-origin runtimes, pass the auth token as a query parameter.
+ // WebSocket connections cannot send custom headers (no Authorization
+ // header), and cross-origin cookies are blocked by browsers, so the
+ // access_token query param is the only way to authenticate.
+ if (!this.isSameOrigin && this.config.authToken) {
+ url.searchParams.set(KnownQueryParams.accessToken, this.config.authToken);
+ }
+
return asWsUrl(url.toString());
}
@@ -143,9 +152,15 @@ export class RuntimeManager {
*/
getLSPURL(lsp: "pylsp" | "basedpyright" | "copilot" | "ty" | "pyrefly"): URL {
if (lsp === "copilot") {
- // For copilot, don't include any query parameters
+ // For copilot, strip all query parameters except the auth token.
+ // Copilot doesn't understand arbitrary query params, but we still
+ // need access_token for cross-origin authentication.
const url = this.formatWsURL(`/lsp/${lsp}`);
+ const accessToken = url.searchParams.get(KnownQueryParams.accessToken);
url.search = "";
+ if (accessToken) {
+ url.searchParams.set(KnownQueryParams.accessToken, accessToken);
+ }
return url;
}
return this.formatWsURL(`/lsp/${lsp}`);
@@ -173,9 +188,10 @@ export class RuntimeManager {
// If there is a redirect, update the URL in the config
if (response.redirected) {
Logger.debug(`Runtime redirected to ${response.url}`);
- // strip /health from the URL
- const baseUrl = response.url.replace(/\/health$/, "");
- this.config.url = baseUrl;
+ // strip /health from the URL, using URL parsing to handle query params
+ const redirected = new URL(response.url);
+ redirected.pathname = redirected.pathname.replace(/\/health$/, "");
+ this.config.url = redirected.toString();
}
const success = response.ok;
@@ -183,7 +199,11 @@ export class RuntimeManager {
this.setDOMBaseUri(this.config.url);
}
return success;
- } catch {
+ } catch (error) {
+ Logger.error(
+ `Failed to check health: ${error instanceof Error ? error.message : "Unknown error"}`,
+ { cause: error },
+ );
return false;
}
}
diff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.py
index 6a5ab8d0d6..e9d10f8a85 100644
--- a/marimo/_server/api/middleware.py
+++ b/marimo/_server/api/middleware.py
@@ -37,7 +37,7 @@ from websockets import ClientConnection, ConnectionClosed, connect
from marimo import _loggers
from marimo._config.settings import GLOBAL_SETTINGS
from marimo._dependencies.dependencies import DependencyManager
-from marimo._server.api.auth import validate_auth
+from marimo._server.api.auth import TOKEN_QUERY_PARAM, validate_auth
from marimo._server.api.deps import AppState, AppStateBase
from marimo._server.codes import WebSocketCodes
from marimo._server.uvicorn_utils import close_uvicorn
@@ -514,10 +514,16 @@ class ProxyMiddleware:
# Re-encode query params from Starlette's already-decoded
# values so spaces become %20 while preserving literal plus
# signs instead of incorrectly treating them as spaces.
+ # Strip the access_token param — it's only used by marimo
+ # for authentication and should not be forwarded to
+ # upstream LSP servers.
encoded_params = [
- (k, quote(v)) for k, v in original_params.items()
+ (k, quote(v))
+ for k, v in original_params.items()
+ if k != TOKEN_QUERY_PARAM
]
- ws_url = f"{ws_url}?{'&'.join(f'{k}={v}' for k, v in encoded_params)}"
+ if encoded_params:
+ ws_url = f"{ws_url}?{'&'.join(f'{k}={v}' for k, v in encoded_params)}"
await websocket.accept()
# Try to connect to the upstream WebSocket with retries
diff --git a/tests/_server/api/test_middleware.py b/tests/_server/api/test_middleware.py
index 8eb6e7049e..fc3183515a 100644
--- a/tests/_server/api/test_middleware.py
+++ b/tests/_server/api/test_middleware.py
@@ -8,10 +8,12 @@ import sys
import time
from multiprocessing import Process
from typing import TYPE_CHECKING, Any
+from urllib.parse import quote
import pytest
import uvicorn
from starlette.applications import Starlette
+from starlette.datastructures import QueryParams
from starlette.responses import Response
from starlette.routing import Route
from starlette.testclient import TestClient
@@ -19,6 +21,7 @@ from starlette.websockets import WebSocket, WebSocketDisconnect
from uvicorn import Config, Server
from marimo._config.manager import MarimoConfigManager, UserConfigManager
+from marimo._server.api.auth import TOKEN_QUERY_PARAM
from marimo._server.api.middleware import (
ProxyMiddleware,
_AsyncHTTPClient,
@@ -654,6 +657,35 @@ class TestProxyMiddleware:
await middleware(scope, None, None)
assert proxy_calls[-1] == "wss://example.com/proxy/test"
+ def test_proxy_websocket_strips_access_token(self) -> None:
+ """access_token is used for marimo auth and must not leak upstream."""
+
+ def _encode_params_without_token(query_string: bytes) -> str:
+ """Reproduce the encoding logic from _proxy_websocket."""
+ params = QueryParams(query_string.decode())
+ encoded = [
+ (k, quote(v))
+ for k, v in params.items()
+ if k != TOKEN_QUERY_PARAM
+ ]
+ if not encoded:
+ return ""
+ return "&".join(f"{k}={v}" for k, v in encoded)
+
+ # access_token should be stripped
+ result = _encode_params_without_token(
+ b"access_token=secret&file=test.py"
+ )
+ assert result == "file=test.py"
+
+ # Only access_token → empty string
+ result = _encode_params_without_token(b"access_token=secret")
+ assert result == ""
+
+ # No access_token → unchanged
+ result = _encode_params_without_token(b"file=test.py&mode=edit")
+ assert result == "file=test.py&mode=edit"
+
def test_proxy_websocket_query_params_space_encoding(self) -> None:
"""Spaces in query params encoded as '+' are re-encoded as '%20'.
@@ -662,9 +694,6 @@ class TestProxyMiddleware:
python-lsp-server expect percent-encoding (%20).
See: https://github.com/marimo-team/marimo/issues/9041
"""
- from urllib.parse import quote
-
- from starlette.datastructures import QueryParams
def _encode_params(query_string: bytes) -> str:
"""Reproduce the encoding logic from _proxy_websocket."""