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 validate callback to asgi with_dynamic_directory (#3081)

Myles Scolnicke0e6ed8b67a3
diff --git a/marimo/_server/asgi.py b/marimo/_server/asgi.py
index 59307b8c51..ab4838e342 100644
--- a/marimo/_server/asgi.py
+++ b/marimo/_server/asgi.py
@@ -3,10 +3,26 @@ from __future__ import annotations
import abc
import logging
+from asyncio import iscoroutine
from pathlib import Path
-from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Tuple
+from typing import (
+ TYPE_CHECKING,
+ Awaitable,
+ Callable,
+ Dict,
+ List,
+ Optional,
+ Tuple,
+ Union,
+)
if TYPE_CHECKING:
+ import sys
+
+ if sys.version_info < (3, 10):
+ from typing_extensions import TypeAlias
+ else:
+ from typing import TypeAlias
from starlette.requests import Request
from starlette.responses import Response
from starlette.types import ASGIApp, Receive, Scope, Send
@@ -22,7 +38,9 @@ class ASGIAppBuilder(abc.ABC):
with_app(path: str, root: str) -> ASGIAppBuilder:
Adds a static application to the ASGI app at the specified path.
- with_dynamic_directory(path: str, directory: str) -> ASGIAppBuilder:
+ with_dynamic_directory(
+ path: str, directory: str, validate_callback: Optional[ValidateCallback] = None
+ ) -> ASGIAppBuilder:
Adds a dynamic directory to the ASGI app, allowing for dynamic loading of applications from the specified directory.
build() -> ASGIApp:
@@ -45,7 +63,11 @@ class ASGIAppBuilder(abc.ABC):
@abc.abstractmethod
def with_dynamic_directory(
- self, *, path: str, directory: str
+ self,
+ *,
+ path: str,
+ directory: str,
+ validate_callback: Optional[ValidateCallback] = None,
) -> "ASGIAppBuilder":
"""
Adds a dynamic directory to the ASGI app, allowing for dynamic loading of applications from the specified directory.
@@ -53,6 +75,11 @@ class ASGIAppBuilder(abc.ABC):
Args:
path (str): The URL path where the dynamic directory will be mounted.
directory (str): The directory containing the applications.
+ validate_callback (Optional[ValidateCallback]): A callback function to validate the application path.
+ This is useful to plug in authentication or authorization checks.
+ The validate_callback receives the application path and the scope,
+ and returns a boolean indicating whether the application is valid.
+ You may also raise an exception for a custom error message.
Returns:
ASGIAppBuilder: The builder instance for chaining.
@@ -70,6 +97,11 @@ class ASGIAppBuilder(abc.ABC):
pass
+ValidateCallback: TypeAlias = Callable[
+ [str, "Scope"], Union[Awaitable[bool], bool]
+]
+
+
class DynamicDirectoryMiddleware:
def __init__(
self,
@@ -77,12 +109,14 @@ class DynamicDirectoryMiddleware:
base_path: str,
directory: str,
app_builder: Callable[[str, str], ASGIApp],
+ validate_callback: Optional[ValidateCallback] = None,
) -> None:
self.app = app
self.base_path = base_path.rstrip("/")
self.directory = Path(directory)
self.app_builder = app_builder
self._app_cache: Dict[str, ASGIApp] = {}
+ self.validate_callback = validate_callback
LOGGER.debug(
f"Initialized DynamicDirectoryMiddleware with base_path={self.base_path}, "
f"directory={self.directory} (exists={self.directory.exists()}, "
@@ -111,7 +145,8 @@ class DynamicDirectoryMiddleware:
self, relative_path: str
) -> Optional[Tuple[Path, str]]:
"""Find a matching Python file in the directory structure.
- Returns tuple of (matching file, remaining path) if found, None otherwise."""
+ Returns tuple of (matching file, remaining path) if found, None otherwise.
+ """
# Try direct match first, skip if relative path has an extension
if not Path(relative_path).suffix:
direct_match = self.directory / f"{relative_path}.py"
@@ -138,25 +173,49 @@ class DynamicDirectoryMiddleware:
async def __call__(
self, scope: Scope, receive: Receive, send: Send
) -> None:
- path = scope["path"]
-
if scope["type"] not in ("http", "websocket"):
- LOGGER.debug(
- f"Non-HTTP/WS request type: {scope['type']}, passing through"
- )
await self.app(scope, receive, send)
return
- # Only handle requests starting with the base_path
- if not path.startswith(f"{self.base_path}/"):
- LOGGER.debug(
- f"Path {path} doesn't start with base_path {self.base_path}/, passing through"
- )
+ path = scope["path"]
+ if not path.startswith(self.base_path + "/"):
await self.app(scope, receive, send)
return
+ app_path = path[len(self.base_path) + 1 :]
+
+ # Empty path or starts with an underscore is not a valid app
+ if not app_path or app_path.startswith("/_"):
+ await self.app(scope, receive, send)
+ return
+
+ # Add validation check
+ if self.validate_callback:
+ from starlette.responses import Response
+
+ try:
+ valid = self.validate_callback(app_path, scope)
+ if iscoroutine(valid):
+ valid = await valid
+ except Exception as e:
+ status_code = getattr(e, "status_code", 500)
+ headers = getattr(e, "headers", None)
+ response = Response(
+ status_code=status_code, headers=headers, content=str(e)
+ )
+ await response(scope, receive, send)
+ return
+
+ if not valid:
+ LOGGER.debug(
+ f"Validate callback returned False for {app_path}, ",
+ )
+ response = Response(status_code=404)
+ await response(scope, receive, send)
+ return
+
# Extract the relative path after the base_path
- relative_path = path[len(self.base_path) + 1 :]
+ relative_path = app_path
if not relative_path:
LOGGER.debug("Empty relative_path, passing through")
await self.app(scope, receive, send)
@@ -347,7 +406,9 @@ def create_asgi_app(
class Builder(ASGIAppBuilder):
def __init__(self) -> None:
self._mount_configs: List[Tuple[str, str]] = []
- self._dynamic_directory_configs: List[Tuple[str, str]] = []
+ self._dynamic_directory_configs: List[
+ Tuple[str, str, Optional[ValidateCallback]]
+ ] = []
self._app_cache: Dict[str, ASGIApp] = {}
def with_app(self, *, path: str, root: str) -> "ASGIAppBuilder":
@@ -355,9 +416,15 @@ def create_asgi_app(
return self
def with_dynamic_directory(
- self, *, path: str, directory: str
+ self,
+ *,
+ path: str,
+ directory: str,
+ validate_callback: Optional[ValidateCallback] = None,
) -> "ASGIAppBuilder":
- self._dynamic_directory_configs.append((path, directory))
+ self._dynamic_directory_configs.append(
+ (path, directory, validate_callback)
+ )
return self
@staticmethod
@@ -428,12 +495,17 @@ def create_asgi_app(
# Add dynamic directory middleware for each directory config
app: ASGIApp = base_app
- for path, directory in self._dynamic_directory_configs:
+ for (
+ path,
+ directory,
+ validate_callback,
+ ) in self._dynamic_directory_configs:
app = DynamicDirectoryMiddleware(
app=app,
base_path=path,
directory=directory,
app_builder=self._create_app_for_file,
+ validate_callback=validate_callback,
)
return app
diff --git a/tests/_server/test_asgi.py b/tests/_server/test_asgi.py
index 84e06f80c4..a0eb78169f 100644
--- a/tests/_server/test_asgi.py
+++ b/tests/_server/test_asgi.py
@@ -2,6 +2,7 @@ import os
import tempfile
import unittest
from pathlib import Path
+from typing import Any
from starlette.applications import Starlette
from starlette.requests import Request
@@ -401,3 +402,95 @@ class TestDynamicDirectoryMiddleware(unittest.TestCase):
response = self.client.get("/apps/nested/nonexistent/")
assert response.status_code == 404
assert response.text == "Not Found"
+
+ def test_validate_callback(self):
+ # Create test files
+ allowed_file = Path(self.temp_dir) / "allowed_app.py"
+ allowed_file.write_text(contents)
+
+ blocked_file = Path(self.temp_dir) / "blocked_app.py"
+ blocked_file.write_text(contents)
+
+ async def async_validate(app_path: str, scope: Any):
+ del scope
+ # Only allow apps with "allowed" in the name
+ return app_path.startswith("allowed")
+
+ middleware = DynamicDirectoryMiddleware(
+ app=self.base_app,
+ base_path="/apps",
+ directory=self.temp_dir,
+ app_builder=default_app_builder,
+ validate_callback=async_validate,
+ )
+ client = TestClient(middleware)
+
+ # Allowed app should work
+ response = client.get("/apps/allowed_app/")
+ assert response.status_code == 200
+
+ # Blocked app should fail
+ response = client.get("/apps/blocked_app/")
+ assert response.status_code == 404
+
+ def test_sync_validate_callback(self):
+ # Create test files
+ allowed_file = Path(self.temp_dir) / "allowed_app.py"
+ allowed_file.write_text(contents)
+
+ blocked_file = Path(self.temp_dir) / "blocked_app.py"
+ blocked_file.write_text(contents)
+
+ def sync_validate(app_path: str, scope: Any):
+ del scope
+ return app_path.startswith("allowed")
+
+ middleware = DynamicDirectoryMiddleware(
+ app=self.base_app,
+ base_path="/apps",
+ directory=self.temp_dir,
+ app_builder=default_app_builder,
+ validate_callback=sync_validate,
+ )
+ client = TestClient(middleware)
+
+ # Allowed app should work
+ response = client.get("/apps/allowed_app/")
+ assert response.status_code == 200
+
+ # Blocked app should fail
+ response = client.get("/apps/blocked_app/")
+ assert response.status_code == 404
+
+ def test_validate_custom_exception(self):
+ from starlette.exceptions import HTTPException
+
+ async def async_validate(app_path: str, scope: Any):
+ del app_path
+ del scope
+ raise HTTPException(status_code=403)
+
+ middleware = DynamicDirectoryMiddleware(
+ app=self.base_app,
+ base_path="/apps",
+ directory=self.temp_dir,
+ app_builder=default_app_builder,
+ validate_callback=async_validate,
+ )
+
+ client = TestClient(middleware)
+ response = client.get("/apps/blocked_app/")
+ assert response.status_code == 403
+ assert response.text == "403: Forbidden"
+
+
+def default_app_builder(base_url: str, file_path: str) -> Starlette:
+ del base_url
+ app = Starlette()
+
+ async def handle(request: Request) -> Response:
+ del request
+ return PlainTextResponse(f"App from {Path(file_path).stem}")
+
+ app.add_route("/{path:path}", handle)
+ return app