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.

fix: validate auth-token on websocket (#6284)

Myles Scolnick2beaf09d3da0
diff --git a/marimo/_server/api/deps.py b/marimo/_server/api/deps.py
index cfee77faa5..01492b904a 100644
--- a/marimo/_server/api/deps.py
+++ b/marimo/_server/api/deps.py
@@ -120,6 +120,10 @@ class AppStateBase:
def asset_url(self) -> Optional[str]:
return getattr(self.state, "asset_url", None)
+ @property
+ def enable_auth(self) -> bool:
+ return getattr(self.state, "enable_auth", True)
+
class AppState(AppStateBase):
"""The app state with a request."""
diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.py
index 872b38890c..180a343b85 100644
--- a/marimo/_server/api/endpoints/ws.py
+++ b/marimo/_server/api/endpoints/ws.py
@@ -26,6 +26,7 @@ from marimo._messaging.ops import (
from marimo._messaging.types import KernelMessage, NoopStream
from marimo._plugins.core.web_component import JSONType
from marimo._runtime.params import QueryParams
+from marimo._server.api.auth import validate_auth
from marimo._server.api.deps import AppState
from marimo._server.codes import WebSocketCodes
from marimo._server.file_router import MarimoFileKey
@@ -68,6 +69,14 @@ async def websocket_endpoint(
description: Websocket endpoint
"""
app_state = AppState(websocket)
+
+ # Validate authentication before proceeding
+ if app_state.enable_auth and not validate_auth(websocket):
+ await websocket.close(
+ WebSocketCodes.UNAUTHORIZED, "MARIMO_UNAUTHORIZED"
+ )
+ return
+
raw_session_id = app_state.query_params(SESSION_QUERY_PARAM_KEY)
if raw_session_id is None:
await websocket.close(
@@ -115,6 +124,15 @@ async def ws_sync(
"""
Websocket endpoint for LoroDoc synchronization
"""
+ app_state = AppState(websocket)
+
+ # Validate authentication before proceeding
+ if app_state.enable_auth and not validate_auth(websocket):
+ await websocket.close(
+ WebSocketCodes.UNAUTHORIZED, "MARIMO_UNAUTHORIZED"
+ )
+ return
+
if not (LORO_ALLOWED and DependencyManager.loro.has()):
if not LORO_ALLOWED:
LOGGER.warning("RTC: Python version is not supported")
diff --git a/marimo/_server/asgi.py b/marimo/_server/asgi.py
index 0a541b8eed..111f8622a6 100644
--- a/marimo/_server/asgi.py
+++ b/marimo/_server/asgi.py
@@ -468,6 +468,7 @@ def create_asgi_app(
redirect_console_to_browser=False,
ttl_seconds=None,
)
+ enable_auth = not AuthToken.is_empty(auth_token)
app = create_starlette_app(
base_url="",
lifespan=Lifespans(
@@ -478,13 +479,14 @@ def create_asgi_app(
*LIFESPAN_REGISTRY.get_all(),
]
),
- enable_auth=not AuthToken.is_empty(auth_token),
+ enable_auth=enable_auth,
allow_origins=("*",),
skew_protection=skew_protection,
)
app.state.session_manager = session_manager
app.state.base_url = base_url
app.state.config_manager = config_reader
+ app.state.enable_auth = enable_auth
return app
def build(self) -> ASGIApp:
diff --git a/marimo/_server/codes.py b/marimo/_server/codes.py
index 41acecfcbb..9e7dc84d10 100644
--- a/marimo/_server/codes.py
+++ b/marimo/_server/codes.py
@@ -6,4 +6,5 @@ class WebSocketCodes(IntEnum):
ALREADY_CONNECTED = 1003
NORMAL_CLOSE = 1000
FORBIDDEN = 1008
+ UNAUTHORIZED = 3000
UNEXPECTED_ERROR = 1011
diff --git a/marimo/_server/start.py b/marimo/_server/start.py
index 4404668f9f..2d0a5c1d70 100644
--- a/marimo/_server/start.py
+++ b/marimo/_server/start.py
@@ -256,12 +256,13 @@ def start(
lifespans_list.append(mcp_server_lifespan)
(external_port, external_host) = _resolve_proxy(port, host, proxy)
+ enable_auth = not AuthToken.is_empty(session_manager.auth_token)
app = create_starlette_app(
base_url=base_url,
host=external_host,
lifespan=Lifespans(lifespans_list),
allow_origins=allow_origins,
- enable_auth=not AuthToken.is_empty(session_manager.auth_token),
+ enable_auth=enable_auth,
lsp_servers=list(lsp_composite_server.servers.values())
if lsp_composite_server is not None
else None,
@@ -281,6 +282,7 @@ def start(
app.state.remote_url = remote_url
app.state.mcp_server_enabled = mcp
app.state.skew_protection = skew_protection
+ app.state.enable_auth = enable_auth
# Resource initialization
# Increase the limit on open file descriptors to prevent resource
diff --git a/tests/_server/api/endpoints/test_execution.py b/tests/_server/api/endpoints/test_execution.py
index 9ed08b70d0..210787a3f5 100644
--- a/tests/_server/api/endpoints/test_execution.py
+++ b/tests/_server/api/endpoints/test_execution.py
@@ -118,7 +118,7 @@ class TestExecutionRoutes_EditMode:
@staticmethod
def test_restart_session(client: TestClient) -> None:
with client.websocket_connect(
- f"/ws?session_id={SESSION_ID}"
+ f"/ws?session_id={SESSION_ID}&access_token=fake-token"
) as websocket:
data = websocket.receive_text()
assert data
diff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.py
index fa941db62d..32f4c1c73f 100644
--- a/tests/_server/api/endpoints/test_resume_session.py
+++ b/tests/_server/api/endpoints/test_resume_session.py
@@ -77,8 +77,12 @@ def get_session(
return get_session_manager(client).get_session(session_id)
+def _create_ws_url(session_id: str) -> str:
+ return f"/ws?session_id={session_id}&access_token=fake-token"
+
+
def test_refresh_session(client: TestClient) -> None:
- with client.websocket_connect("/ws?session_id=123") as websocket:
+ with client.websocket_connect(_create_ws_url("123")) as websocket:
data = websocket.receive_json()
print(data)
assert_kernel_ready_response(data, create_response({}))
@@ -97,7 +101,7 @@ def test_refresh_session(client: TestClient) -> None:
# New session with new ID (simulates refresh)
# We should resume the current session
- with client.websocket_connect("/ws?session_id=456") as websocket:
+ with client.websocket_connect(_create_ws_url("456")) as websocket:
# First message is the kernel reconnected
data = websocket.receive_json()
assert data == {"op": "reconnected", "data": {"op": "reconnected"}}
@@ -129,7 +133,7 @@ def test_refresh_session(client: TestClient) -> None:
# New session again
# We should not resume the current session with the new values
- with client.websocket_connect("/ws?session_id=789") as websocket:
+ with client.websocket_connect(_create_ws_url("789")) as websocket:
# First message is the kernel reconnected
data = websocket.receive_json()
assert data == {"op": "reconnected", "data": {"op": "reconnected"}}
@@ -164,7 +168,7 @@ def test_save_session(client: TestClient) -> None:
.file_router.get_single_app_file_manager()
.filename
)
- with client.websocket_connect("/ws?session_id=123") as websocket:
+ with client.websocket_connect(_create_ws_url("123")) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data, create_response({}))
# Send save request
@@ -197,7 +201,7 @@ def test_save_session(client: TestClient) -> None:
# New session with new ID (simulates refresh)
# We should resume the current session
- with client.websocket_connect("/ws?session_id=456") as websocket:
+ with client.websocket_connect(_create_ws_url("456")) as websocket:
# First message is the kernel reconnected
data = websocket.receive_json()
assert data == {"op": "reconnected", "data": {"op": "reconnected"}}
@@ -239,7 +243,7 @@ def test_save_session(client: TestClient) -> None:
def test_save_config(client: TestClient) -> None:
- with client.websocket_connect("/ws?session_id=123") as websocket:
+ with client.websocket_connect(_create_ws_url("123")) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data, create_response({}))
# Send save request
@@ -266,7 +270,7 @@ def test_save_config(client: TestClient) -> None:
def test_restart_session(client: TestClient) -> None:
- with client.websocket_connect("/ws?session_id=123") as websocket:
+ with client.websocket_connect(_create_ws_url("123")) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data, create_response({}))
@@ -283,7 +287,7 @@ def test_restart_session(client: TestClient) -> None:
# New session with new ID (simulates refresh)
# We start a new session
- with client.websocket_connect("/ws?session_id=456") as websocket:
+ with client.websocket_connect(_create_ws_url("456")) as websocket:
# First message is the kernel reconnected
data = websocket.receive_json()
assert_kernel_ready_response(
@@ -300,7 +304,7 @@ def test_resume_session_with_watch(client: TestClient) -> None:
session_manager = get_session_manager(client)
session_manager.watch = True
- with client.websocket_connect("/ws?session_id=123") as websocket:
+ with client.websocket_connect(_create_ws_url("123")) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data, create_response({}))
@@ -335,7 +339,7 @@ def test_resume_session_with_watch(client: TestClient) -> None:
# Resume session with new ID (simulates refresh)
# watcher_on_save is 'autorun', so we should expect the cell to be run
- with client.websocket_connect("/ws?session_id=456") as websocket:
+ with client.websocket_connect(_create_ws_url("456")) as websocket:
# First message is the kernel reconnected
data = websocket.receive_json()
assert data == {"op": "reconnected", "data": {"op": "reconnected"}}
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index 168e055d42..95642b229b 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -56,6 +56,14 @@ def headers(session_id: str) -> dict[str, str]:
}
+def _create_ws_url(session_id: str) -> str:
+ return f"/ws?session_id={session_id}&access_token=fake-token"
+
+
+WS_URL = _create_ws_url("123")
+OTHER_WS_URL = _create_ws_url("456")
+
+
def assert_kernel_ready_response(
raw_data: dict[str, Any], response: Optional[dict[str, Any]] = None
) -> None:
@@ -81,7 +89,7 @@ def assert_parse_ready_response(raw_data: dict[str, Any]) -> None:
def test_ws(client: TestClient) -> None:
- with client.websocket_connect("/ws?session_id=123") as websocket:
+ with client.websocket_connect(WS_URL) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data)
# shut down after websocket context manager exists, otherwise
@@ -91,7 +99,7 @@ def test_ws(client: TestClient) -> None:
def test_without_session(client: TestClient) -> None:
with pytest.raises(WebSocketDisconnect) as exc_info:
- with client.websocket_connect("/ws"):
+ with client.websocket_connect("/ws?access_token=fake-token"):
raise AssertionError()
assert exc_info.value.code == 1000
assert exc_info.value.reason == "MARIMO_NO_SESSION_ID"
@@ -99,11 +107,11 @@ def test_without_session(client: TestClient) -> None:
def test_disconnect_and_reconnect(client: TestClient) -> None:
- with client.websocket_connect("/ws?session_id=123") as websocket:
+ with client.websocket_connect(WS_URL) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data)
# Connect by the same session id
- with client.websocket_connect("/ws?session_id=123") as websocket:
+ with client.websocket_connect(WS_URL) as websocket:
data = websocket.receive_json()
assert data == {"op": "reconnected", "data": {"op": "reconnected"}}
data = websocket.receive_json()
@@ -113,18 +121,18 @@ def test_disconnect_and_reconnect(client: TestClient) -> None:
def test_disconnect_then_reconnect_then_refresh(client: TestClient) -> None:
- with client.websocket_connect("/ws?session_id=123") as websocket:
+ with client.websocket_connect(WS_URL) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data)
websocket.close()
# Connect by the same session id
- with client.websocket_connect("/ws?session_id=123") as websocket:
+ with client.websocket_connect(WS_URL) as websocket:
data = websocket.receive_json()
assert data == {"op": "reconnected", "data": {"op": "reconnected"}}
data = websocket.receive_json()
assert data["op"] == "alert"
# New session with new ID (simulates refresh)
- with client.websocket_connect("/ws?session_id=456") as websocket:
+ with client.websocket_connect(OTHER_WS_URL) as websocket:
data = websocket.receive_json()
assert data == {"op": "reconnected", "data": {"op": "reconnected"}}
data = websocket.receive_json()
@@ -137,13 +145,11 @@ def test_allows_multiple_connections_with_other_sessions(
client: TestClient,
) -> None:
with rtc_enabled(get_user_config_manager(client)):
- with client.websocket_connect("/ws?session_id=123") as websocket:
+ with client.websocket_connect(WS_URL) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data)
# Should allow second connection
- with client.websocket_connect(
- "/ws?session_id=456"
- ) as other_websocket:
+ with client.websocket_connect(OTHER_WS_URL) as other_websocket:
data = other_websocket.receive_json()
assert_kernel_ready_response(
data, create_response({"resumed": True})
@@ -154,13 +160,11 @@ def test_allows_multiple_connections_with_other_sessions(
def test_fails_on_multiple_connections_with_other_sessions(
client: TestClient,
) -> None:
- with client.websocket_connect("/ws?session_id=123") as websocket:
+ with client.websocket_connect(WS_URL) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data)
with pytest.raises(WebSocketDisconnect) as exc_info: # noqa: PT012
- with client.websocket_connect(
- "/ws?session_id=456"
- ) as other_websocket:
+ with client.websocket_connect(OTHER_WS_URL) as other_websocket:
other_websocket.receive_json()
raise AssertionError()
assert exc_info.value.code == 1003
@@ -172,9 +176,10 @@ def test_allows_multiple_connections_with_same_file(
client: TestClient,
temp_marimo_file: str,
) -> None:
+ del temp_marimo_file
with rtc_enabled(get_user_config_manager(client)):
- ws_1 = f"/ws?session_id=123&file={temp_marimo_file}"
- ws_2 = f"/ws?session_id=456&file={temp_marimo_file}"
+ ws_1 = WS_URL
+ ws_2 = _create_ws_url("456")
with client.websocket_connect(ws_1) as websocket:
data = websocket.receive_json()
assert_parse_ready_response(data)
@@ -189,8 +194,8 @@ def test_fails_on_multiple_connections_with_same_file(
client: TestClient,
temp_marimo_file: str,
) -> None:
- ws_1 = f"/ws?session_id=123&file={temp_marimo_file}"
- ws_2 = f"/ws?session_id=456&file={temp_marimo_file}"
+ ws_1 = f"{WS_URL}&file={temp_marimo_file}"
+ ws_2 = f"{OTHER_WS_URL}&file={temp_marimo_file}"
with client.websocket_connect(ws_1) as websocket:
data = websocket.receive_json()
assert_parse_ready_response(data)
@@ -207,7 +212,7 @@ def test_fails_on_multiple_connections_with_same_file(
async def test_file_watcher_calls_reload(client: TestClient) -> None:
session_manager: SessionManager = get_session_manager(client)
session_manager.watch = True
- with client.websocket_connect("/ws?session_id=123") as websocket:
+ with client.websocket_connect(WS_URL) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data)
session_manager.mode = SessionMode.RUN
@@ -228,7 +233,7 @@ async def test_file_watcher_calls_reload(client: TestClient) -> None:
async def test_query_params(client: TestClient) -> None:
with client.websocket_connect(
- "/ws?session_id=123&foo=1&bar=2&bar=3&baz=4"
+ f"{WS_URL}&foo=1&bar=2&bar=3&baz=4"
) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data)
@@ -246,7 +251,7 @@ async def test_query_params(client: TestClient) -> None:
async def test_connect_kiosk_without_session(client: TestClient) -> None:
with pytest.raises(WebSocketDisconnect) as exc_info: # noqa: PT012
with client.websocket_connect(
- "/ws?session_id=123&kiosk=true"
+ "/ws?session_id=123&kiosk=true&access_token=fake-token"
) as websocket:
websocket.receive_json()
raise AssertionError()
@@ -257,13 +262,13 @@ async def test_connect_kiosk_without_session(client: TestClient) -> None:
async def test_connect_kiosk_with_session(client: TestClient) -> None:
# Create the first session
- with client.websocket_connect("/ws?session_id=123") as websocket:
+ with client.websocket_connect(WS_URL) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data)
# Connect by the same session id in kiosk mode
with client.websocket_connect(
- "/ws?session_id=123&kiosk=true"
+ f"{WS_URL}&kiosk=true"
) as other_websocket:
data = other_websocket.receive_json()
assert_kernel_ready_response(
@@ -278,14 +283,14 @@ async def test_cannot_connect_kiosk_with_run_session(
# Create the first session
session_manager = get_session_manager(client)
session_manager.mode = SessionMode.RUN
- with client.websocket_connect("/ws?session_id=123") as websocket:
+ with client.websocket_connect(WS_URL) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data)
# Connect by the same session id in kiosk mode
with pytest.raises(WebSocketDisconnect) as exc_info: # noqa: PT012
with client.websocket_connect(
- "/ws?session_id=123&kiosk=true"
+ f"{WS_URL}&kiosk=true"
) as other_websocket:
data = other_websocket.receive_json()
raise AssertionError()
@@ -300,8 +305,8 @@ async def test_connects_to_existing_session_with_same_file(
client: TestClient,
temp_marimo_file: str,
) -> None:
- ws_1 = f"/ws?session_id=123&file={temp_marimo_file}"
- ws_2 = f"/ws?session_id=456&file={temp_marimo_file}"
+ ws_1 = f"{WS_URL}&file={temp_marimo_file}"
+ ws_2 = f"{OTHER_WS_URL}&file={temp_marimo_file}"
with rtc_enabled(get_user_config_manager(client)):
with client.websocket_connect(ws_1) as websocket1:
@@ -362,3 +367,42 @@ def rtc_enabled(config: UserConfigManager):
yield
finally:
config.save_config(prev_config)
+
+
+def test_ws_requires_authentication(client: TestClient) -> None:
+ """Test that WebSocket connections require authentication."""
+ # Try to connect without any authentication headers
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ with client.websocket_connect("/ws"):
+ raise AssertionError("Should not be able to connect without auth")
+
+ assert exc_info.value.code == WebSocketCodes.UNAUTHORIZED
+ assert exc_info.value.reason == "MARIMO_UNAUTHORIZED"
+
+ # Ensure shutdown
+ try:
+ client.post("/api/kernel/shutdown", headers=HEADERS)
+ except Exception:
+ pass
+
+
+def test_ws_sync_requires_authentication(client: TestClient) -> None:
+ """Test that WebSocket sync endpoint requires authentication."""
+ # Try to connect without any authentication headers
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ with client.websocket_connect("/ws_sync?file=test"):
+ raise AssertionError("Should not be able to connect without auth")
+
+ assert exc_info.value.code == WebSocketCodes.UNAUTHORIZED
+ assert exc_info.value.reason == "MARIMO_UNAUTHORIZED"
+
+
+def test_ws_with_valid_authentication(client: TestClient) -> None:
+ """Test that WebSocket connections work with valid authentication."""
+ # Connect with proper authentication headers
+ with client.websocket_connect(WS_URL, headers=HEADERS) as websocket:
+ data = websocket.receive_json()
+ assert_kernel_ready_response(data)
+
+ # Clean up
+ client.post("/api/kernel/shutdown", headers=HEADERS)
diff --git a/tests/_server/api/endpoints/test_ws_rtc.py b/tests/_server/api/endpoints/test_ws_rtc.py
index 3eeb98731a..760a6b1aaf 100644
--- a/tests/_server/api/endpoints/test_ws_rtc.py
+++ b/tests/_server/api/endpoints/test_ws_rtc.py
@@ -101,16 +101,18 @@ def rtc_enabled(config: UserConfigManager):
config.save_config(prev_config)
+# Set up unique websocket paths for each client
+ws_1 = "/ws?session_id=123&access_token=fake-token"
+ws_2 = "/ws?session_id=456&access_token=fake-token"
+
+# Set up unique synchronization websocket paths for each client
+ws_1_sync = "/ws_sync?session_id=123&access_token=fake-token"
+ws_2_sync = "/ws_sync?session_id=456&access_token=fake-token"
+
+
@pytest.mark.skipif("sys.version_info < (3, 11)")
async def test_loro_sync(client: TestClient) -> None:
"""Test that Loro-CRDT sync works between multiple clients"""
- # Set up unique websocket paths for each client
- ws_1 = "/ws?session_id=123"
- ws_2 = "/ws?session_id=456"
-
- # Set up unique synchronization websocket paths for each client
- ws_1_sync = "/ws_sync?session_id=123"
- ws_2_sync = "/ws_sync?session_id=456"
# First connect main websockets to create sessions
with (
@@ -161,13 +163,13 @@ async def test_loro_cleanup_on_session_close(
with (
rtc_enabled(get_user_config_manager(client)),
- client.websocket_connect("/ws?session_id=123") as websocket,
+ client.websocket_connect(ws_1) as websocket,
):
data = websocket.receive_json()
assert_kernel_ready_response(data)
# Connect to cell websocket
- with client.websocket_connect("/ws_sync?session_id=123") as cell_ws:
+ with client.websocket_connect(ws_1_sync) as cell_ws:
sync_msg = cell_ws.receive_bytes()
assert len(sync_msg) > 0
@@ -202,12 +204,12 @@ async def test_loro_persistence(client: TestClient) -> None:
# First connection sets initial code
with (
rtc_enabled(get_user_config_manager(client)),
- client.websocket_connect("/ws?session_id=123") as websocket,
+ client.websocket_connect(ws_1) as websocket,
):
data = websocket.receive_json()
assert_kernel_ready_response(data)
- with client.websocket_connect("/ws_sync?session_id=123") as cell_ws1:
+ with client.websocket_connect(ws_1_sync) as cell_ws1:
sync_msg = cell_ws1.receive_bytes()
assert len(sync_msg) > 0
@@ -224,12 +226,12 @@ async def test_loro_persistence(client: TestClient) -> None:
# Second connection should receive persisted code
with (
rtc_enabled(get_user_config_manager(client)),
- client.websocket_connect("/ws?session_id=456") as websocket,
+ client.websocket_connect(ws_2) as websocket,
):
data = websocket.receive_json()
assert_kernel_ready_response(data, create_response({"resumed": True}))
- with client.websocket_connect("/ws_sync?session_id=456") as cell_ws2:
+ with client.websocket_connect(ws_2_sync) as cell_ws2:
sync_msg = cell_ws2.receive_bytes()
# Verify initial sync contains data
assert len(sync_msg) > 0
diff --git a/tests/_server/api/test_auth.py b/tests/_server/api/test_auth.py
index 62b1ef8dd7..1f3a3b2728 100644
--- a/tests/_server/api/test_auth.py
+++ b/tests/_server/api/test_auth.py
@@ -57,6 +57,7 @@ def app() -> Starlette:
app.state.host = "localhost"
app.state.port = 1234
app.state.base_url = ""
+ app.state.enable_auth = True
return app