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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: better logging in SkewProtection middleware (#4169)
Myles Scolnickf35263bf9ae8
diff --git a/marimo/_server/api/auth.py b/marimo/_server/api/auth.pyindex 5319286c40..cc672fabca 100644--- a/marimo/_server/api/auth.py+++ b/marimo/_server/api/auth.py@@ -40,6 +40,7 @@ def validate_auth(# Check for session cookiecookie_session = CookieSession(conn.session)+# Validate the cookieif cookie_session.get_access_token() == auth_token:return True # Success@@ -48,7 +49,7 @@ def validate_auth(if TOKEN_QUERY_PARAM in conn.query_params:# Validate the access_tokenif conn.query_params[TOKEN_QUERY_PARAM] == auth_token:- LOGGER.debug("Validated access_token")+ LOGGER.debug("Validated access_token from query param")# Set the cookiecookie_session.set_access_token(auth_token)return True # Success@@ -58,11 +59,12 @@ def validate_auth(# Validate the access_tokenpassword = form_dict.get("password")if password == auth_token:- LOGGER.debug("Validated access_token")+ LOGGER.debug("Validated access_token from form data")# Set the cookiecookie_session.set_access_token(auth_token)return Trueelse:+ LOGGER.warning("Invalid password from form data.")return False# Check for basic auth@@ -70,7 +72,7 @@ def validate_auth(if auth is not None:username, password = _parse_basic_auth_header(auth)if username and password == auth_token:- LOGGER.debug("Validated basic auth")+ LOGGER.debug("Validated basic auth from header")# Set the cookiecookie_session.set_access_token(auth_token)cookie_session.set_username(username)diff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.pyindex e5443fe789..332102b8cc 100644--- a/marimo/_server/api/middleware.py+++ b/marimo/_server/api/middleware.py@@ -9,6 +9,7 @@ from typing import (TYPE_CHECKING,Any,Callable,+ Final,Optional,Union,)@@ -79,6 +80,8 @@ class AuthBackend(AuthenticationBackend):class SkewProtectionMiddleware:+ HEADER_NAME: Final[str] = "Marimo-Server-Token"+def __init__(self, app: ASGIApp) -> None:self.app = app@@ -106,8 +109,27 @@ class SkewProtectionMiddleware:return await self.app(scope, receive, send)expected = state.session_manager.skew_protection_token- server_token = request.headers.get("Marimo-Server-Token")+ server_token = request.headers.get(self.HEADER_NAME)+ if server_token is None:+ LOGGER.warning(+ "Received request with no server token (skew protection token). "+ "This could mean the header is being stripped by a proxy. "+ "If you are running behind a proxy, please ensure the header "+ f"'{self.HEADER_NAME}' is being forwarded."+ )+ response = JSONResponse(+ {"error": "Missing server token"},+ status_code=status.HTTP_401_UNAUTHORIZED,+ )+ return await response(scope, receive, send)+if server_token != str(expected):+ LOGGER.warning(+ "Received request with invalid server token (skew protection token). "+ "This could mean the server has new code deployed but the client "+ "is still using an old version."+ f"Expected: {expected}, got: {server_token}"+ )response = JSONResponse({"error": "Invalid server token"},status_code=status.HTTP_401_UNAUTHORIZED,diff --git a/marimo/_server/api/utils.py b/marimo/_server/api/utils.pyindex d38ed5039a..17621a01e1 100644--- a/marimo/_server/api/utils.py+++ b/marimo/_server/api/utils.py@@ -5,6 +5,7 @@ import osimport subprocessimport sysimport webbrowser+from pathlib import Pathfrom shutil import whichfrom typing import TYPE_CHECKING, Optional, TypeVar@@ -14,22 +15,6 @@ if TYPE_CHECKING:from starlette.requests import Request-# TODO still needed?-def require_header(header: list[str] | None) -> str:- """- Require exactly one value in header and return it.- """-- if header is None:- raise ValueError("Expected exactly one value in header, got None")- if len(header) != 1:- raise ValueError(- "Expected exactly one value in header, "- f"got {len(header)} values: {header}"- )- return header[0]--async def parse_request(request: Request, cls: type[T], allow_unknown_keys: bool = False) -> T:@@ -48,7 +33,7 @@ def parse_title(filepath: Optional[str]) -> str:# filename is used as title, except basename and suffix are# stripped and underscores are replaced with spaces- return os.path.splitext(os.path.basename(filepath))[0].replace("_", " ")+ return Path(filepath).stem.replace("_", " ")def open_url_in_browser(browser: str, url: str) -> None:diff --git a/tests/_server/test_utils.py b/tests/_server/test_utils.pyindex e284b7883f..93ebfd380a 100644--- a/tests/_server/test_utils.py+++ b/tests/_server/test_utils.py@@ -1,28 +1,7 @@# Copyright 2024 Marimo. All rights reserved.-import pytest+from __future__ import annotations-from marimo._server.api.utils import parse_title, require_header---def test_require_header() -> None:- # Happy path- header = ["Content-Type"]- assert require_header(header) == "Content-Type", (- "The function should return the single header value"- )-- with pytest.raises(ValueError) as e:- require_header(None)- assert str(e.value) == "Expected exactly one value in header, got None"-- # Test case 3: ValueError is raised when an empty list is passed as the- # header- with pytest.raises(ValueError) as e:- require_header([])- assert (- str(e.value)- == "Expected exactly one value in header, got 0 values: []"- )+from marimo._server.api.utils import parse_title# The function to be tested