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: check frontend's app matches server's app in run mode (#449)

Akshay Agrawal6c38c265b1c3
diff --git a/marimo/_server/api/code_complete.py b/marimo/_server/api/code_complete.py
index 16063d819e..3adf0ca3a9 100644
--- a/marimo/_server/api/code_complete.py
+++ b/marimo/_server/api/code_complete.py
@@ -6,7 +6,7 @@ from dataclasses import dataclass
from marimo._ast.cell import CellId_t
from marimo._runtime import requests
from marimo._server import sessions
-from marimo._server.api.edit_handler import EditHandler
+from marimo._server.api.validated_handler import ValidatedHandler
from marimo._utils.parse_dataclass import parse_raw
@@ -17,7 +17,7 @@ class CodeComplete:
cell_id: CellId_t
-class CodeCompleteHandler(EditHandler):
+class CodeCompleteHandler(ValidatedHandler):
"""Complete a code fragment."""
@sessions.requires_edit
diff --git a/marimo/_server/api/delete.py b/marimo/_server/api/delete.py
index 5ac76f88a8..0a7281f95c 100644
--- a/marimo/_server/api/delete.py
+++ b/marimo/_server/api/delete.py
@@ -6,7 +6,7 @@ from dataclasses import dataclass
from marimo._ast.cell import CellId_t
from marimo._runtime import requests
from marimo._server import sessions
-from marimo._server.api.edit_handler import EditHandler
+from marimo._server.api.validated_handler import ValidatedHandler
from marimo._utils.parse_dataclass import parse_raw
@@ -15,7 +15,7 @@ class Delete:
cell_id: CellId_t
-class DeleteHandler(EditHandler):
+class DeleteHandler(ValidatedHandler):
"""Delete a cell with a given id"""
@sessions.requires_edit
diff --git a/marimo/_server/api/directory_autocomplete.py b/marimo/_server/api/directory_autocomplete.py
index 8d3f6905bf..39797e4927 100644
--- a/marimo/_server/api/directory_autocomplete.py
+++ b/marimo/_server/api/directory_autocomplete.py
@@ -5,7 +5,7 @@ import os
from dataclasses import dataclass
from marimo._server import sessions
-from marimo._server.api.edit_handler import EditHandler
+from marimo._server.api.validated_handler import ValidatedHandler
from marimo._utils.parse_dataclass import parse_raw
@@ -14,7 +14,7 @@ class DirectoryAutocomplete:
prefix: str
-class DirectoryAutocompleteHandler(EditHandler):
+class DirectoryAutocompleteHandler(ValidatedHandler):
"""Complete a path to subdirectories and Python files."""
@sessions.requires_edit
diff --git a/marimo/_server/api/format.py b/marimo/_server/api/format.py
index bef0c7dcfa..95d7e88562 100644
--- a/marimo/_server/api/format.py
+++ b/marimo/_server/api/format.py
@@ -7,7 +7,7 @@ from typing import Dict
from marimo import _loggers
from marimo._ast import cell
from marimo._server import sessions
-from marimo._server.api.edit_handler import EditHandler
+from marimo._server.api.validated_handler import ValidatedHandler
from marimo._utils.parse_dataclass import parse_raw
LOGGER = _loggers.marimo_logger()
@@ -19,7 +19,7 @@ class Format:
codes: Dict[cell.CellId_t, str]
-class FormatHandler(EditHandler):
+class FormatHandler(ValidatedHandler):
"""Save an app to disk."""
@sessions.requires_edit
diff --git a/marimo/_server/api/function_call.py b/marimo/_server/api/function_call.py
index e2eb6659c7..1f9e1db074 100644
--- a/marimo/_server/api/function_call.py
+++ b/marimo/_server/api/function_call.py
@@ -4,11 +4,10 @@ from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Dict
-import tornado.web
-
from marimo import _loggers
from marimo._runtime import requests
from marimo._server import sessions
+from marimo._server.api.validated_handler import ValidatedHandler
from marimo._utils.parse_dataclass import parse_raw
LOGGER = _loggers.marimo_logger()
@@ -23,7 +22,7 @@ class FunctionCall:
args: Dict[str, Any]
-class FunctionHandler(tornado.web.RequestHandler):
+class FunctionHandler(ValidatedHandler):
"""Invoke an RPC"""
def post(self) -> None:
diff --git a/marimo/_server/api/instantiate.py b/marimo/_server/api/instantiate.py
index 1d1102e876..ee7ad6f61b 100644
--- a/marimo/_server/api/instantiate.py
+++ b/marimo/_server/api/instantiate.py
@@ -4,11 +4,10 @@ from __future__ import annotations
from dataclasses import dataclass
from typing import Any, List
-import tornado.web
-
from marimo._ast.app import App
from marimo._runtime import requests
from marimo._server import sessions
+from marimo._server.api.validated_handler import ValidatedHandler
from marimo._utils.parse_dataclass import parse_raw
@@ -20,7 +19,7 @@ class Instantiate:
values: List[Any]
-class InstantiateHandler(tornado.web.RequestHandler):
+class InstantiateHandler(ValidatedHandler):
"""Instantiate an app
Run all cells, parametrized by values for UI elements, if any.
@@ -31,6 +30,7 @@ class InstantiateHandler(tornado.web.RequestHandler):
args = parse_raw(self.request.body, Instantiate)
mgr = sessions.get_manager()
app = mgr.load_app()
+
execution_requests: tuple[requests.ExecutionRequest, ...]
if app is None:
# Instantiating an empty app
diff --git a/marimo/_server/api/interrupt.py b/marimo/_server/api/interrupt.py
index 5bc584626a..ced04fde31 100644
--- a/marimo/_server/api/interrupt.py
+++ b/marimo/_server/api/interrupt.py
@@ -2,10 +2,10 @@
from __future__ import annotations
from marimo._server import sessions
-from marimo._server.api.edit_handler import EditHandler
+from marimo._server.api.validated_handler import ValidatedHandler
-class InterruptHandler(EditHandler):
+class InterruptHandler(ValidatedHandler):
"""Interrupt the kernel's execution."""
@sessions.requires_edit
diff --git a/marimo/_server/api/read_code.py b/marimo/_server/api/read_code.py
index 392a11a645..928ec9aafd 100644
--- a/marimo/_server/api/read_code.py
+++ b/marimo/_server/api/read_code.py
@@ -4,11 +4,11 @@ from __future__ import annotations
import tornado.web
from marimo._server import sessions
-from marimo._server.api.edit_handler import EditHandler
from marimo._server.api.status import HTTPStatus
+from marimo._server.api.validated_handler import ValidatedHandler
-class ReadCodeHandler(EditHandler):
+class ReadCodeHandler(ValidatedHandler):
"""Handler for reading code from the server."""
@sessions.requires_edit
diff --git a/marimo/_server/api/rename.py b/marimo/_server/api/rename.py
index fb1f26e9c6..f3d9716c8b 100644
--- a/marimo/_server/api/rename.py
+++ b/marimo/_server/api/rename.py
@@ -9,7 +9,7 @@ import tornado.web
from marimo import _loggers
from marimo._server import sessions
from marimo._server.api import status
-from marimo._server.api.edit_handler import EditHandler
+from marimo._server.api.validated_handler import ValidatedHandler
from marimo._server.utils import canonicalize_filename
from marimo._utils.parse_dataclass import parse_raw
@@ -21,7 +21,7 @@ class Rename:
filename: str
-class RenameHandler(EditHandler):
+class RenameHandler(ValidatedHandler):
"""Rename the current app."""
@sessions.requires_edit
diff --git a/marimo/_server/api/run.py b/marimo/_server/api/run.py
index 0e07db2806..90242ed921 100644
--- a/marimo/_server/api/run.py
+++ b/marimo/_server/api/run.py
@@ -7,7 +7,7 @@ from typing import List
from marimo._ast.cell import CellId_t
from marimo._runtime import requests
from marimo._server import sessions
-from marimo._server.api.edit_handler import EditHandler
+from marimo._server.api.validated_handler import ValidatedHandler
from marimo._utils.parse_dataclass import parse_raw
@@ -19,7 +19,7 @@ class Run:
codes: List[str]
-class RunHandler(EditHandler):
+class RunHandler(ValidatedHandler):
"""Run multiple cells (and their descendants).
Updates cell code in the kernel if needed; registers new cells
diff --git a/marimo/_server/api/save.py b/marimo/_server/api/save.py
index aacde6b1e7..9701029312 100644
--- a/marimo/_server/api/save.py
+++ b/marimo/_server/api/save.py
@@ -11,8 +11,8 @@ from marimo import _loggers
from marimo._ast import codegen
from marimo._ast.cell import CellConfig
from marimo._server import sessions
-from marimo._server.api.edit_handler import EditHandler
from marimo._server.api.status import HTTPStatus
+from marimo._server.api.validated_handler import ValidatedHandler
from marimo._server.layout import LayoutConfig, save_layout_config
from marimo._server.utils import canonicalize_filename
from marimo._utils.parse_dataclass import parse_raw
@@ -34,7 +34,7 @@ class Save:
layout: Optional[Dict[str, Any]] = None
-class SaveHandler(EditHandler):
+class SaveHandler(ValidatedHandler):
"""Save an app to disk."""
@sessions.requires_edit
diff --git a/marimo/_server/api/save_app_config.py b/marimo/_server/api/save_app_config.py
index 6d6c061301..70bc262e52 100644
--- a/marimo/_server/api/save_app_config.py
+++ b/marimo/_server/api/save_app_config.py
@@ -9,8 +9,8 @@ import tornado.web
from marimo import _loggers
from marimo._ast import codegen
from marimo._server import sessions
-from marimo._server.api.edit_handler import EditHandler
from marimo._server.api.status import HTTPStatus
+from marimo._server.api.validated_handler import ValidatedHandler
from marimo._utils.parse_dataclass import parse_raw
LOGGER = _loggers.marimo_logger()
@@ -22,7 +22,7 @@ class SaveAppConfiguration:
config: Dict[str, Any]
-class SaveAppConfigurationHandler(EditHandler):
+class SaveAppConfigurationHandler(ValidatedHandler):
"""Save app configuration to session manager."""
@sessions.requires_edit
diff --git a/marimo/_server/api/save_user_config.py b/marimo/_server/api/save_user_config.py
index d497b0a155..7128626db4 100644
--- a/marimo/_server/api/save_user_config.py
+++ b/marimo/_server/api/save_user_config.py
@@ -13,8 +13,8 @@ from marimo._config.config import MarimoConfig, configure
from marimo._config.utils import get_config_path
from marimo._runtime import requests
from marimo._server import sessions
-from marimo._server.api.edit_handler import EditHandler
from marimo._server.api.status import HTTPStatus
+from marimo._server.api.validated_handler import ValidatedHandler
from marimo._utils.parse_dataclass import parse_raw
LOGGER = _loggers.marimo_logger()
@@ -45,7 +45,7 @@ class SaveUserConfiguration:
config: MarimoConfig
-class SaveUserConfigurationHandler(EditHandler):
+class SaveUserConfigurationHandler(ValidatedHandler):
"""Save user configuration to disk."""
@sessions.requires_edit
diff --git a/marimo/_server/api/set_cell_config.py b/marimo/_server/api/set_cell_config.py
index be3ed3fd69..aadd26b870 100644
--- a/marimo/_server/api/set_cell_config.py
+++ b/marimo/_server/api/set_cell_config.py
@@ -4,11 +4,10 @@ from __future__ import annotations
from dataclasses import dataclass
from typing import Dict
-import tornado.web
-
from marimo._ast.cell import CellId_t
from marimo._runtime import requests
from marimo._server import sessions
+from marimo._server.api.validated_handler import ValidatedHandler
from marimo._utils.parse_dataclass import parse_raw
@@ -18,18 +17,7 @@ class SetCellConfig:
configs: Dict[CellId_t, Dict[str, object]]
-class SetCellConfigHandler(tornado.web.RequestHandler):
- # This mutates cell config in the kernel.
- #
- # NB: Checking server token?
- #
- # - To prevent a frontend from accidentally setting the config of a kernel
- # it wasn't started for (eg, frontend created locally on a port that's
- # forwarded to a remote server for a different marimo app), we could
- # require a server token.
- # - But currently we don't check the server token in run mode to allow
- # connecting to a marimo server that died and came back, without
- # refreshing the page
+class SetCellConfigHandler(ValidatedHandler):
def post(self) -> None:
session = sessions.require_session_from_header(self.request.headers)
args = parse_raw(self.request.body, SetCellConfig)
diff --git a/marimo/_server/api/set_ui_element_value.py b/marimo/_server/api/set_ui_element_value.py
index fd5523c02c..ef2aaf5f66 100644
--- a/marimo/_server/api/set_ui_element_value.py
+++ b/marimo/_server/api/set_ui_element_value.py
@@ -4,10 +4,9 @@ from __future__ import annotations
from dataclasses import dataclass
from typing import Any, List
-import tornado.web
-
from marimo._runtime import requests
from marimo._server import sessions
+from marimo._server.api.validated_handler import ValidatedHandler
from marimo._utils.parse_dataclass import parse_raw
@@ -19,7 +18,7 @@ class SetUIElementValue:
values: List[Any]
-class SetUIElementValueHandler(tornado.web.RequestHandler):
+class SetUIElementValueHandler(ValidatedHandler):
def post(self) -> None:
session = sessions.require_session_from_header(self.request.headers)
args = parse_raw(self.request.body, SetUIElementValue)
diff --git a/marimo/_server/api/edit_handler.py b/marimo/_server/api/validated_handler.py
similarity index 74%
rename from marimo/_server/api/edit_handler.py
rename to marimo/_server/api/validated_handler.py
index d53458d076..95a32678af 100644
--- a/marimo/_server/api/edit_handler.py
+++ b/marimo/_server/api/validated_handler.py
@@ -6,8 +6,8 @@ import tornado.web
from marimo._server import sessions
-class EditHandler(tornado.web.RequestHandler):
- """Checks that the frontend has a token matching the edit session."""
+class ValidatedHandler(tornado.web.RequestHandler):
+ """Checks that the frontend has a token matching the server."""
def prepare(self) -> None:
# Validate the server token -- don't allow connections from frontends
diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.py
index c30d1af505..347e69be1a 100644
--- a/marimo/_server/sessions.py
+++ b/marimo/_server/sessions.py
@@ -218,7 +218,7 @@ class IOSocketHandler(tornado.websocket.WebSocketHandler):
self.status = ConnectionState.CLOSED
mgr = get_manager()
if mgr.mode == SessionMode.RUN:
- # TODO: keep alive
+
def _close() -> None:
if self.status != ConnectionState.OPEN:
LOGGER.debug(
@@ -403,13 +403,25 @@ class SessionManager:
self.sessions: dict[str, Session] = {}
self.app_config: Optional[_AppConfig]
# token uniquely identifying this server
- self.server_token = str(uuid4())
if (app := self.load_app()) is not None:
self.app_config = app._config
else:
self.app_config = None
+ if mode == SessionMode.EDIT:
+ # In edit mode, the server gets a random token to prevent
+ # frontends that it didn't create from connecting to it and
+ # executing edit-only commands (such as overwriting the file).
+ self.server_token = str(uuid4())
+ else:
+ # Because run-mode is read-only, all that matters is that
+ # the frontend's app matches the server's app.
+ assert app is not None
+ self.server_token = str(
+ hash("".join(code for code in app._codes()))
+ )
+
def load_app(self) -> Optional[App]:
return codegen.get_app(self.filename)
diff --git a/marimo/_smoke_tests/status.py b/marimo/_smoke_tests/status.py
index 8e2d2fdeaf..ed26b468f2 100644
--- a/marimo/_smoke_tests/status.py
+++ b/marimo/_smoke_tests/status.py
@@ -1,3 +1,4 @@
+# Copyright 2023 Marimo. All rights reserved.
import marimo
__generated_with = "0.1.63"