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: apply origin settings to WebSocket connections (#11621)

Myles Scolnickf88ec50fae2f
diff --git a/docs/guides/deploying/deploying_nginx.md b/docs/guides/deploying/deploying_nginx.md
index 2645d6d14a..c9922ce0ee 100644
--- a/docs/guides/deploying/deploying_nginx.md
+++ b/docs/guides/deploying/deploying_nginx.md
@@ -17,7 +17,7 @@ server {
server_name your-domain.com;
location / {
- proxy_set_header Host $host;
+ proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
@@ -41,6 +41,8 @@ server {
- `server_name`: Replace with your domain name
- `proxy_pass`: Points to your marimo application (default port is 2718)
+- `Host $http_host`: Preserves the public hostname and port
+- `X-Forwarded-Proto $scheme`: Passes the public HTTP or HTTPS scheme to marimo
- WebSocket support: The following lines are required for marimo to function properly:
```nginx
@@ -56,9 +58,13 @@ server {
1. Start your marimo application:
```bash
-marimo run app.py --host 127.0.0.1 --port 2718
+marimo run app.py --host 127.0.0.1 --port 2718 --allow-origins http://your-domain.com
```
+Replace `http://your-domain.com` with the public origin that users open in their browser.
+For HTTPS, use `https://your-domain.com`.
+These options also apply to `marimo edit`.
+
2. Test your nginx configuration:
```bash
@@ -79,6 +85,29 @@ For production deployments, it's recommended to use HTTPS. You can use [Certbot]
## Common Issues
+### WebSocket connection returns HTTP 403
+
+WebSocket connections use the public origin from the browser.
+A proxy can change the `Host` header or the scheme before the request reaches marimo.
+This can cause the origin comparison to fail.
+
+If the public hostname differs from `--host`, set `--allow-origins` to the public origin.
+This configuration also applies when the proxy changes `Host`:
+
+```bash
+marimo run app.py --host 127.0.0.1 --port 2718 --allow-origins https://your-domain.com
+```
+
+An origin contains a scheme and a hostname, plus a port for non-default ports, such as `https://your-domain.com:8443`.
+It has no path or trailing slash, even for applications with a `--base-url`.
+For multiple public origins, repeat `--allow-origins`.
+The `X-Forwarded-Host` header does not replace this configuration.
+
+For HTTPS connections, retain `proxy_set_header X-Forwarded-Proto $scheme` in nginx.
+Uvicorn uses this header only from trusted proxies.
+If nginx connects from an address other than `127.0.0.1`, set `FORWARDED_ALLOW_IPS` to the proxy addresses before you start marimo.
+Use a comma-separated list of the proxy addresses, as described in [Uvicorn's configuration](https://uvicorn.dev/settings/#http).
+
### Kernel Not Found
If you see a "kernel not found" error, ensure that:
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index ed786cb36d..bbba663061 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -347,7 +347,10 @@ class _OptionalValueOption(click.Option):
"--allow-origins",
default=None,
multiple=True,
- help="Allowed origins for CORS. Can be repeated. Use * for all origins.",
+ help=(
+ "Allowed origins for HTTP and WebSocket connections. "
+ "Can be repeated. Use * for all origins."
+ ),
)
@click.option(
"--skip-update-check",
@@ -1077,7 +1080,9 @@ Example:
"--allow-origins",
default=None,
multiple=True,
- help="Allowed origins for CORS. Can be repeated.",
+ help=(
+ "Allowed origins for HTTP and WebSocket connections. Can be repeated."
+ ),
)
@click.option(
"--redirect-console-to-browser",
diff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.py
index 87d8b2bc84..b87fa1701f 100644
--- a/marimo/_server/api/middleware.py
+++ b/marimo/_server/api/middleware.py
@@ -6,6 +6,7 @@ import time
from collections.abc import AsyncIterable, Callable
from dataclasses import dataclass
from http.client import HTTPResponse, HTTPSConnection
+from ipaddress import ip_address
from typing import (
TYPE_CHECKING,
Any,
@@ -109,6 +110,116 @@ class AuthBackend(AuthenticationBackend):
raise ValueError(f"Invalid session mode: {mode}")
+class WebSocketOriginMiddleware:
+ """Apply the server's origin policy to WebSocket handshakes."""
+
+ def __init__(
+ self,
+ app: ASGIApp,
+ *,
+ allow_origins: tuple[str, ...] = (),
+ host: str | None = None,
+ ) -> None:
+ self.app = app
+ self.trusted_hosts = {"localhost", "127.0.0.1", "::1"}
+ if host is not None:
+ self.trusted_hosts.add(host.strip("[]").lower())
+ self.allow_all_origins = "*" in allow_origins
+ self.allow_origins: set[tuple[str, str, int]] = set()
+ for value in allow_origins:
+ if value == "*":
+ continue
+ origin = self._parse_origin(value)
+ if origin is None:
+ LOGGER.warning(
+ "Ignoring invalid WebSocket origin %r in allow_origins. "
+ "Use an http:// or https:// origin with an optional port, "
+ "without a path or trailing slash.",
+ value,
+ )
+ else:
+ self.allow_origins.add(origin)
+
+ @staticmethod
+ def _parse_origin(value: str) -> tuple[str, str, int] | None:
+ if (
+ not value.isprintable()
+ or any(char.isspace() for char in value)
+ or "\\" in value
+ ):
+ return None
+ try:
+ parsed = urlparse(value)
+ if (
+ parsed.scheme not in ("http", "https")
+ or not parsed.hostname
+ or parsed.username is not None
+ or parsed.password is not None
+ or parsed.netloc.endswith(":")
+ or parsed.path
+ or parsed.params
+ or "?" in value
+ or "#" in value
+ ):
+ return None
+ port = parsed.port
+ authority = parsed.hostname
+ if ":" in authority:
+ authority = f"[{authority}]"
+ if port is not None:
+ authority += ":" + parsed.netloc.rsplit(":", 1)[1]
+ if authority.lower() != parsed.netloc.lower():
+ return None
+ if port is None:
+ port = 443 if parsed.scheme == "https" else 80
+ return parsed.scheme, parsed.hostname, port
+ except ValueError:
+ return None
+
+ def _is_trusted_host(self, hostname: str, scope: Scope) -> bool:
+ if hostname in self.trusted_hosts:
+ return True
+ server = scope.get("server")
+ if server is None:
+ return False
+ try:
+ # The local socket address also supports direct IP connections.
+ return ip_address(hostname) == ip_address(server[0])
+ except ValueError:
+ return False
+
+ async def __call__(
+ self, scope: Scope, receive: Receive, send: Send
+ ) -> None:
+ if scope["type"] != "websocket":
+ return await self.app(scope, receive, send)
+
+ websocket = WebSocket(scope, receive, send)
+ origins = websocket.headers.getlist("origin")
+ # Non-browser clients may omit Origin.
+ if not origins:
+ return await self.app(scope, receive, send)
+
+ origin = self._parse_origin(origins[0]) if len(origins) == 1 else None
+ scheme = "https" if scope["scheme"] == "wss" else "http"
+ server_origin = self._parse_origin(
+ f"{scheme}://{websocket.headers.get('host', '')}"
+ )
+ if origin is not None and (
+ (
+ origin == server_origin
+ and self._is_trusted_host(origin[1], scope)
+ )
+ or origin in self.allow_origins
+ or self.allow_all_origins
+ ):
+ return await self.app(scope, receive, send)
+
+ await websocket.close(
+ code=WebSocketCodes.FORBIDDEN, reason="Origin not allowed"
+ )
+
+
class SkewProtectionMiddleware:
HEADER_NAME: Final[str] = "Marimo-Server-Token"
diff --git a/marimo/_server/main.py b/marimo/_server/main.py
index ac98876be0..814fbf705c 100644
--- a/marimo/_server/main.py
+++ b/marimo/_server/main.py
@@ -23,6 +23,7 @@ from marimo._server.api.middleware import (
ProxyMiddleware,
SkewProtectionMiddleware,
TimeoutMiddleware,
+ WebSocketOriginMiddleware,
)
from marimo._server.api.router import build_routes
from marimo._server.errors import handle_error
@@ -60,9 +61,14 @@ def create_starlette_app(
skew_protection: bool = True,
timeout: float | None = None,
) -> Starlette:
- # Handle host API requests first to bypass the editor's middleware.
final_middlewares: list[Middleware] = [
- Middleware(HostApiMiddleware, base_url=base_url)
+ Middleware(
+ WebSocketOriginMiddleware,
+ allow_origins=allow_origins or (),
+ host=host,
+ ),
+ # Handle host API requests before the editor's middleware.
+ Middleware(HostApiMiddleware, base_url=base_url),
]
if allow_origins is None:
diff --git a/tests/_server/api/test_middleware.py b/tests/_server/api/test_middleware.py
index 6467f87b81..b6ce321a18 100644
--- a/tests/_server/api/test_middleware.py
+++ b/tests/_server/api/test_middleware.py
@@ -997,11 +997,11 @@ class TestLspProxyAuth:
def exchange():
client = TestClient(app)
with client.websocket_connect(
- "/notebook/lsp/test-lsp/ws",
+ "ws://localhost/notebook/lsp/test-lsp/ws",
headers={
**token_header("fake-token"),
"Marimo-LSP-Token": "client-cannot-override-this",
- "Origin": "http://testserver",
+ "Origin": "http://localhost",
},
) as websocket:
websocket.send_text("LSP message")
diff --git a/tests/_server/api/test_websocket_origin.py b/tests/_server/api/test_websocket_origin.py
new file mode 100644
index 0000000000..2b7d727650
--- /dev/null
+++ b/tests/_server/api/test_websocket_origin.py
@@ -0,0 +1,371 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import logging
+
+import pytest
+from starlette.applications import Starlette
+from starlette.middleware import Middleware
+from starlette.responses import PlainTextResponse
+from starlette.routing import Route, WebSocketRoute
+from starlette.testclient import TestClient
+from starlette.websockets import WebSocket, WebSocketDisconnect
+from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
+
+from marimo._server.api.middleware import WebSocketOriginMiddleware
+from marimo._server.main import create_starlette_app
+from tests._server.mocks import get_mock_session_manager
+
+
+async def echo(websocket: WebSocket) -> None:
+ await websocket.accept()
+ await websocket.send_text("connected")
+ await websocket.close()
+
+
+def make_client(
+ allow_origins: tuple[str, ...] = (), *, host: str | None = None
+) -> TestClient:
+ return TestClient(
+ Starlette(
+ routes=[
+ WebSocketRoute("/ws", echo),
+ Route("/", lambda _: PlainTextResponse("ok")),
+ ],
+ middleware=[
+ Middleware(
+ WebSocketOriginMiddleware,
+ allow_origins=allow_origins,
+ host=host,
+ )
+ ],
+ )
+ )
+
+
+ ("url", "origin"),
+ [
+ ("ws://localhost:2718/ws", "http://localhost:2718"),
+ ("ws://127.0.0.1:2718/ws", "http://127.0.0.1:2718"),
+ ("ws://[::1]:2718/ws", "http://[::1]:2718"),
+ ("ws://example.com/ws", "http://example.com:80"),
+ ("ws://example.com:80/ws", "http://example.com"),
+ ("wss://example.com/ws", "https://example.com:443"),
+ ("wss://example.com:443/ws", "https://example.com"),
+ ("wss://example.com:8443/ws", "https://EXAMPLE.COM:8443"),
+ ("ws://localhost:2718/ws", None),
+ ],
+)
+def test_same_origin(url: str, origin: str | None) -> None:
+ headers = {"Origin": origin} if origin is not None else {}
+ with make_client(host="example.com").websocket_connect(
+ url, headers=headers
+ ) as websocket:
+ assert websocket.receive_text() == "connected"
+
+
+ "origin",
+ [
+ "http://other.example",
+ "http://localhost:8080",
+ "http://127.0.0.1:2718",
+ "https://localhost:2718",
+ "http://localhost:2718.other.example",
+ "http://localhost:[email protected]",
+ "http://other.example@localhost:2718",
+ "http://localhost:2718/path",
+ "http://localhost:2718?",
+ "http://localhost:2718#",
+ "http://localhost:invalid",
+ "http://localhost:99999",
+ "http://[::1",
+ "http://local\\host:2718",
+ "http://local\thost:2718",
+ "http://localhost:2718 http://other.example",
+ "http://localhost:2718,http://other.example",
+ "ws://localhost:2718",
+ "localhost",
+ "null",
+ "",
+ ],
+)
+def test_other_or_invalid_origin(origin: str) -> None:
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ with make_client().websocket_connect(
+ "ws://localhost:2718/ws", headers={"Origin": origin}
+ ):
+ pytest.fail("Unexpected connection")
+ assert (exc_info.value.code, exc_info.value.reason) == (
+ 1008,
+ "Origin not allowed",
+ )
+
+
[email protected]("allow_origins", [(), ("*",)])
+def test_duplicate_origin(allow_origins: tuple[str, ...]) -> None:
+ client = make_client(allow_origins)
+ client.headers = [("Origin", "http://localhost")] * 2
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ with client.websocket_connect("ws://localhost/ws"):
+ pytest.fail("Unexpected connection")
+ assert exc_info.value.reason == "Origin not allowed"
+
+
[email protected]("allow_origins", [(), ("*",)])
+ "origin",
+ [
+ "null",
+ "",
+ "\x00http://[::1]",
+ "http://[::1]\x7f",
+ "http://[::1]:",
+ "http://[::1]extra",
+ "http://[::1]extra:80",
+ "http://[::1]/",
+ "http://[::1]?query",
+ "http://[::1]#fragment",
+ "http://user:password@[::1]",
+ ],
+)
+def test_invalid_origin_with_configured_policy(
+ allow_origins: tuple[str, ...], origin: str
+) -> None:
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ with make_client(allow_origins).websocket_connect(
+ "ws://[::1]/ws", headers={"Origin": origin}
+ ):
+ pytest.fail("Unexpected connection")
+ assert exc_info.value.reason == "Origin not allowed"
+
+
+ "allow_origins", [("https://editor.example",), ("*",)]
+)
+def test_configured_origins(allow_origins: tuple[str, ...]) -> None:
+ client = make_client(allow_origins)
+ with client.websocket_connect(
+ "/ws", headers={"Origin": "https://editor.example"}
+ ) as websocket:
+ assert websocket.receive_text() == "connected"
+ with client.websocket_connect(
+ "ws://localhost/ws", headers={"Origin": "http://localhost"}
+ ) as websocket:
+ assert websocket.receive_text() == "connected"
+
+
+ "allow_origins", [("https://editor.example",), ("localhost",)]
+)
+def test_configured_origins_require_full_match(
+ allow_origins: tuple[str, ...],
+) -> None:
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ with make_client(allow_origins).websocket_connect(
+ "/ws", headers={"Origin": "https://editor.example:8443"}
+ ):
+ pytest.fail("Unexpected connection")
+ assert exc_info.value.reason == "Origin not allowed"
+
+
+def test_configured_origins_normalize_host_and_port() -> None:
+ client = make_client(("https://EDITOR.example:443",))
+ with client.websocket_connect(
+ "/ws", headers={"Origin": "https://editor.example"}
+ ) as websocket:
+ assert websocket.receive_text() == "connected"
+
+
+def test_invalid_configured_origins_warn_once(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ with caplog.at_level(logging.WARNING):
+ client = make_client(
+ (
+ "localhost",
+ "https://editor.example/",
+ "https://editor.example",
+ "*",
+ )
+ )
+ for _ in range(2):
+ with client.websocket_connect(
+ "/ws", headers={"Origin": "https://editor.example"}
+ ) as websocket:
+ assert websocket.receive_text() == "connected"
+ assert [record.getMessage() for record in caplog.records] == [
+ f"Ignoring invalid WebSocket origin {origin!r} in allow_origins. "
+ "Use an http:// or https:// origin with an optional port, "
+ "without a path or trailing slash."
+ for origin in ("localhost", "https://editor.example/")
+ ]
+
+
[email protected]("host", ["localhost", "0.0.0.0", "::"])
+def test_bound_host_does_not_allow_other_origins(host: str) -> None:
+ app = create_starlette_app(base_url="", host=host, enable_auth=False)
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ with TestClient(app).websocket_connect(
+ "ws://localhost:2718/ws",
+ headers={"Origin": "http://localhost:8080"},
+ ):
+ pytest.fail("Unexpected connection")
+ assert exc_info.value.reason == "Origin not allowed"
+
+
[email protected]("host", [None, "localhost", "0.0.0.0", "::"])
[email protected]("enable_auth", [True, False])
[email protected]("request_host", ["other.example", "192.0.2.50"])
+def test_matching_headers_require_a_configured_host(
+ host: str | None, enable_auth: bool, request_host: str
+) -> None:
+ app = create_starlette_app(base_url="", host=host, enable_auth=enable_auth)
+ app.state.session_manager = get_mock_session_manager()
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ with TestClient(app).websocket_connect(
+ "ws://127.0.0.1:2718/ws?access_token=fake-token",
+ headers={
+ "Host": f"{request_host}:2718",
+ "Origin": f"http://{request_host}:2718",
+ },
+ ):
+ pytest.fail("Unexpected connection")
+ assert exc_info.value.reason == "Origin not allowed"
+
+
+def test_configured_host_is_allowed() -> None:
+ app = create_starlette_app(
+ base_url="", host="EDITOR.EXAMPLE", enable_auth=False
+ )
+ app.state.session_manager = get_mock_session_manager()
+ app.router.routes.insert(0, WebSocketRoute("/echo", echo))
+ with TestClient(app).websocket_connect(
+ "ws://127.0.0.1:2718/echo",
+ headers={
+ "Host": "editor.example:8080",
+ "Origin": "http://editor.example:8080",
+ },
+ ) as websocket:
+ assert websocket.receive_text() == "connected"
+
+
[email protected]("host", ["192.0.2.10", "[2001:db8::1]"])
+def test_local_socket_address_is_allowed(host: str) -> None:
+ with make_client().websocket_connect(
+ f"ws://{host}:2718/ws", headers={"Origin": f"http://{host}:2718"}
+ ) as websocket:
+ assert websocket.receive_text() == "connected"
+
+
+def test_socket_hostname_does_not_allow_other_origins() -> None:
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ with make_client().websocket_connect(
+ "ws://other.example/ws",
+ headers={"Origin": "http://other.example"},
+ ):
+ pytest.fail("Unexpected connection")
+ assert exc_info.value.reason == "Origin not allowed"
+
+
+def test_rewritten_host_with_configured_origin() -> None:
+ with make_client(("https://editor.example",)).websocket_connect(
+ "ws://127.0.0.1:2718/ws",
+ headers={
+ "Host": "internal-upstream:2718",
+ "Origin": "https://editor.example",
+ },
+ ) as websocket:
+ assert websocket.receive_text() == "connected"
+
+
+def test_http_and_lifespan_passthrough() -> None:
+ with make_client() as client:
+ response = client.get("/", headers={"Origin": "https://other.example"})
+ assert response.text == "ok"
+
+
+def test_trusted_proxy_scheme() -> None:
+ client = TestClient(
+ ProxyHeadersMiddleware(
+ make_client(host="example.com").app, trusted_hosts=["testclient"]
+ )
+ )
+ with client.websocket_connect(
+ "ws://127.0.0.1:2718/ws",
+ headers={
+ "Host": "example.com",
+ "Origin": "https://example.com",
+ "X-Forwarded-Proto": "https",
+ },
+ ) as websocket:
+ assert websocket.receive_text() == "connected"
+
+
+def test_forwarded_headers_are_not_used_directly() -> None:
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ with make_client().websocket_connect(
+ "ws://localhost:2718/ws",
+ headers={
+ "Origin": "https://other.example",
+ "X-Forwarded-Proto": "https",
+ "X-Forwarded-Host": "other.example",
+ },
+ ):
+ pytest.fail("Unexpected connection")
+ assert exc_info.value.reason == "Origin not allowed"
+
+
[email protected]("enable_auth", [True, False])
[email protected]("base_url", ["", "/notebook"])
+ "path",
+ [
+ "/ws",
+ "/ws_sync",
+ "/terminal/ws",
+ "/lsp/pylsp",
+ "/api/marimo/v1/notebooks/test/events/ws",
+ ],
+)
+def test_app_websocket_origins(
+ enable_auth: bool, base_url: str, path: str
+) -> None:
+ app = create_starlette_app(
+ base_url=base_url, enable_auth=enable_auth, skew_protection=False
+ )
+ app.state.session_manager = get_mock_session_manager()
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ with TestClient(app).websocket_connect(
+ f"{base_url}{path}?access_token=fake-token",
+ headers={"Origin": "https://other.example"},
+ ):
+ pytest.fail("Unexpected connection")
+ assert (exc_info.value.code, exc_info.value.reason) == (
+ 1008,
+ "Origin not allowed",
+ )
+
+
[email protected]("enable_auth", [True, False])
+ "allow_origins", [None, ("https://editor.example",), ("*",)]
+)
+def test_app_allowed_origins(
+ enable_auth: bool, allow_origins: tuple[str, ...] | None
+) -> None:
+ app = create_starlette_app(
+ base_url="", enable_auth=enable_auth, allow_origins=allow_origins
+ )
+ app.state.session_manager = get_mock_session_manager()
+ app.router.routes.insert(0, WebSocketRoute("/echo", echo))
+ origins = ["http://localhost"]
+ if allow_origins:
+ origins.append("https://editor.example")
+ for origin in origins:
+ with TestClient(app).websocket_connect(
+ "ws://localhost/echo?access_token=fake-token",
+ headers={"Origin": origin},
+ ) as websocket:
+ assert websocket.receive_text() == "connected"