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
Server Token (#367)
Akshay Agrawal2dd0c1e68750
diff --git a/frontend/.storybook/preview-head.html b/frontend/.storybook/preview-head.htmlindex 046d5be921..2ed620bd3b 100644--- a/frontend/.storybook/preview-head.html+++ b/frontend/.storybook/preview-head.html@@ -6,3 +6,4 @@hidden></marimo-user-config><marimo-app-config data-config="{}" hidden></marimo-app-config>+<marimo-server-token data-token="123" hidden></marimo-server-token>diff --git a/frontend/index.html b/frontend/index.htmlindex 1427367816..8d74347247 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -24,6 +24,7 @@<marimo-version data-version={{ version }} hidden></marimo-version><marimo-user-config data-config='{{ user_config }}' hidden></marimo-user-config><marimo-app-config data-config='{{ app_config }}' hidden></marimo-app-config>+ <marimo-server-token data-token='{{ server_token }}' hidden></marimo-server-token><title>{{ title }}</title></head><body>diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex 9e2d4b9b44..d80849c74d 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -1,7 +1,10 @@/* Copyright 2023 Marimo. All rights reserved. */import { z } from "zod";-import { assertExists } from "../../utils/assertExists";import { Logger } from "@/utils/Logger";+import {+ getRawMarimoAppConfig,+ getRawMarimoUserConfig,+} from "../dom/marimo-tag";export const UserConfigSchema = z.object({@@ -55,7 +58,7 @@ export type AppConfig = z.infer<typeof AppConfigSchema>;export function parseAppConfig() {try {- return AppConfigSchema.parse(JSON.parse(getConfig("app")));+ return AppConfigSchema.parse(JSON.parse(getRawMarimoAppConfig()));} catch (error) {throw new Error(`Marimo got an unexpected value in the configuration file: ${error}`@@ -65,7 +68,7 @@ export function parseAppConfig() {export function parseUserConfig() {try {- const parsed = UserConfigSchema.parse(JSON.parse(getConfig("user")));+ const parsed = UserConfigSchema.parse(JSON.parse(getRawMarimoUserConfig()));for (const [key, value] of Object.entries(parsed.experimental)) {if (value === true) {Logger.log(`🧪 Experimental feature "${key}" is enabled.`);@@ -78,14 +81,3 @@ export function parseUserConfig() {);}}--function getConfig(kind: "user" | "app") {- const tagName = kind === "user" ? "marimo-user-config" : "marimo-app-config";- const tag = document.querySelector<HTMLElement>(tagName);- assertExists(tag, `internal-error: ${tagName} tag not found`);-- const configData = tag.dataset.config;- assertExists(configData, "internal-error: missing config");-- return configData;-}diff --git a/frontend/src/core/dom/marimo-tag.ts b/frontend/src/core/dom/marimo-tag.tsnew file mode 100644index 0000000000..324fade49c--- /dev/null+++ b/frontend/src/core/dom/marimo-tag.ts@@ -0,0 +1,35 @@+/* Copyright 2023 Marimo. All rights reserved. */++import { invariant } from "@/utils/invariant";++export function getMarimoVersion(): string {+ return getMarimoDOMValue("marimo-version", "version");+}++export function getMarimoServerToken(): string {+ return getMarimoDOMValue("marimo-server-token", "token");+}++export function getRawMarimoAppConfig(): string {+ return getMarimoDOMValue("marimo-app-config", "config");+}++export function getRawMarimoUserConfig(): string {+ return getMarimoDOMValue("marimo-user-config", "config");+}++function getMarimoDOMValue(tagName: string, key: string) {+ const tag = document.querySelector(tagName);+ invariant(+ tag !== null && tag instanceof HTMLElement,+ `internal-error: ${tagName} tag not found`+ );++ const value = tag.dataset[key];+ invariant(+ value !== undefined,+ `internal-error: ${tagName} tag does not have ${key}`+ );++ return value;+}diff --git a/frontend/src/core/dom/version.ts b/frontend/src/core/dom/version.tsdeleted file mode 100644index c177b7cf1a..0000000000--- a/frontend/src/core/dom/version.ts+++ /dev/null@@ -1,19 +0,0 @@-/* Copyright 2023 Marimo. All rights reserved. */--import { invariant } from "@/utils/invariant";--export function getMarimoVersion() {- const tag = document.querySelector("marimo-version");- invariant(- tag !== null && tag instanceof HTMLElement,- "internal-error: marimo-version tag not found"- );-- const version = tag.dataset.version;- invariant(- version !== undefined,- "internal-error: marimo-version tag does not have version"- );-- return version;-}diff --git a/frontend/src/core/network/api.ts b/frontend/src/core/network/api.tsindex 29c698a3ca..f1ee042b4c 100644--- a/frontend/src/core/network/api.ts+++ b/frontend/src/core/network/api.ts@@ -1,6 +1,8 @@/* Copyright 2023 Marimo. All rights reserved. */+import { once } from "@/utils/once";import { Logger } from "../../utils/Logger";import { UUID } from "../../utils/uuid";+import { getMarimoServerToken } from "../dom/marimo-tag";export function getXsrfCookie(): string {const r = document.cookie.match("\\b_xsrf=([^;]*)\\b");@@ -9,6 +11,10 @@ export function getXsrfCookie(): string {const BASE_URL = "/api";+const getServerTokenOnce = once(() => {+ return getMarimoServerToken();+});+/*** Wrapper around fetch that adds XSRF token and session ID to the request and* strong types.@@ -22,6 +28,7 @@ export const API = {"Content-Type": "application/json","X-Xsrftoken": getXsrfCookie(),"Marimo-Session-Id": UUID,+ "Marimo-Server-Token": getServerTokenOnce(),},body: JSON.stringify(body),})diff --git a/frontend/src/core/static/__tests__/download-html.test.ts b/frontend/src/core/static/__tests__/download-html.test.tsindex 79bbec56c7..dbc3700431 100644--- a/frontend/src/core/static/__tests__/download-html.test.ts+++ b/frontend/src/core/static/__tests__/download-html.test.ts@@ -34,6 +34,7 @@ const DOC = `<marimo-filename hidden="">app.py</marimo-filename><marimo-mode data-mode="edit" hidden=""></marimo-mode><marimo-version data-version="0.1.44" hidden=""></marimo-version>+ <marimo-server-token data-token="123" hidden=""></marimo-server-token><marimo-user-configdata-config='{"display": {"theme": "light"}, "keymap": {"preset": "default"}, "save": {"autosave": "after_delay", "format_on_save": true, "autosave_delay": 1000}, "server": {"browser": "default"}, "experimental": {"layouts": true, "theming": true}, "runtime": {"auto_instantiate": true}, "completion": {"activate_on_typing": true, "copilot": true}}'hidden=""diff --git a/frontend/src/core/static/download-html.ts b/frontend/src/core/static/download-html.tsindex 1c7b8dc987..3010de366c 100644--- a/frontend/src/core/static/download-html.ts+++ b/frontend/src/core/static/download-html.ts@@ -1,6 +1,6 @@/* Copyright 2023 Marimo. All rights reserved. */import { NotebookState, getNotebook } from "../cells/cells";-import { getMarimoVersion } from "../dom/version";+import { getMarimoVersion } from "../dom/marimo-tag";// For Testing:// Flip this to true to use local assets instead of CDNdiff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex 9a63d0e3f5..6b94bbe23a 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -33,6 +33,7 @@ const htmlDevPlugin = (): Plugin => {"marimo-mode","marimo-user-config","marimo-app-config",+ "marimo-server-token",];// remove from devdiff --git a/marimo/_cli/test_cli.py b/marimo/_cli/test_cli.pyindex 607f0510b4..ba6f3bb499 100644--- a/marimo/_cli/test_cli.py+++ b/marimo/_cli/test_cli.py@@ -65,7 +65,7 @@ def test_cli_help_exit_code() -> None:def test_cli_edit() -> None:- # smoke test: makes sure CLI starts+ # smoke test: makes sure CLI starts and has basic things we expect# helpful for catching issues related to# Python 3.8 compatibility, such as forgetting `from __future__` import# annotations@@ -76,6 +76,7 @@ def test_cli_edit() -> None:_check_contents(p, f"marimo-version data-version={__version__}".encode(), contents)+ _check_contents(p, b"marimo-server-token", contents)def test_cli_run() -> None:diff --git a/marimo/_server/api/code_complete.py b/marimo/_server/api/code_complete.pyindex f180dfcc1e..2222fbf4f5 100644--- a/marimo/_server/api/code_complete.py+++ b/marimo/_server/api/code_complete.py@@ -3,11 +3,10 @@ from __future__ import annotationsfrom dataclasses import dataclass-import tornado.web-from marimo._ast.cell import CellId_tfrom marimo._runtime import requestsfrom marimo._server import sessions+from marimo._server.api.validated_handler import ValidatedHandlerfrom marimo._utils.parse_dataclass import parse_raw@@ -18,7 +17,7 @@ class CodeComplete:cell_id: CellId_t-class CodeCompleteHandler(tornado.web.RequestHandler):+class CodeCompleteHandler(ValidatedHandler):"""Complete a path to subdirectories and Python files."""def post(self) -> None:diff --git a/marimo/_server/api/delete.py b/marimo/_server/api/delete.pyindex a4ce467d04..0a7281f95c 100644--- a/marimo/_server/api/delete.py+++ b/marimo/_server/api/delete.py@@ -3,11 +3,10 @@ from __future__ import annotationsfrom dataclasses import dataclass-import tornado.web-from marimo._ast.cell import CellId_tfrom marimo._runtime import requestsfrom marimo._server import sessions+from marimo._server.api.validated_handler import ValidatedHandlerfrom marimo._utils.parse_dataclass import parse_raw@@ -16,7 +15,7 @@ class Delete:cell_id: CellId_t-class DeleteHandler(tornado.web.RequestHandler):+class DeleteHandler(ValidatedHandler):"""Delete a cell with a given id"""@sessions.requires_editdiff --git a/marimo/_server/api/directory_autocomplete.py b/marimo/_server/api/directory_autocomplete.pyindex 739d84d590..7c375b6602 100644--- a/marimo/_server/api/directory_autocomplete.py+++ b/marimo/_server/api/directory_autocomplete.py@@ -4,8 +4,7 @@ from __future__ import annotationsimport osfrom dataclasses import dataclass-import tornado.web-+from marimo._server.api.validated_handler import ValidatedHandlerfrom marimo._utils.parse_dataclass import parse_raw@@ -14,7 +13,7 @@ class DirectoryAutocomplete:prefix: str-class DirectoryAutocompleteHandler(tornado.web.RequestHandler):+class DirectoryAutocompleteHandler(ValidatedHandler):"""Complete a path to subdirectories and Python files."""def post(self) -> None:diff --git a/marimo/_server/api/format.py b/marimo/_server/api/format.pyindex 646a2a160d..95d7e88562 100644--- a/marimo/_server/api/format.py+++ b/marimo/_server/api/format.py@@ -4,11 +4,10 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Dict-import tornado.web-from marimo import _loggersfrom marimo._ast import cellfrom marimo._server import sessions+from marimo._server.api.validated_handler import ValidatedHandlerfrom marimo._utils.parse_dataclass import parse_rawLOGGER = _loggers.marimo_logger()@@ -20,7 +19,7 @@ class Format:codes: Dict[cell.CellId_t, str]-class FormatHandler(tornado.web.RequestHandler):+class FormatHandler(ValidatedHandler):"""Save an app to disk."""@sessions.requires_editdiff --git a/marimo/_server/api/function_call.py b/marimo/_server/api/function_call.pyindex e2eb6659c7..1f9e1db074 100644--- a/marimo/_server/api/function_call.py+++ b/marimo/_server/api/function_call.py@@ -4,11 +4,10 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Any, Dict-import tornado.web-from marimo import _loggersfrom marimo._runtime import requestsfrom marimo._server import sessions+from marimo._server.api.validated_handler import ValidatedHandlerfrom marimo._utils.parse_dataclass import parse_rawLOGGER = _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.pyindex 1d1102e876..3776e21227 100644--- a/marimo/_server/api/instantiate.py+++ b/marimo/_server/api/instantiate.py@@ -4,11 +4,10 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Any, List-import tornado.web-from marimo._ast.app import Appfrom marimo._runtime import requestsfrom marimo._server import sessions+from marimo._server.api.validated_handler import ValidatedHandlerfrom 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 appRun all cells, parametrized by values for UI elements, if any.diff --git a/marimo/_server/api/interrupt.py b/marimo/_server/api/interrupt.pyindex c8314fc2cb..62aecc26fa 100644--- a/marimo/_server/api/interrupt.py+++ b/marimo/_server/api/interrupt.py@@ -1,12 +1,11 @@# Copyright 2023 Marimo. All rights reserved.from __future__ import annotations-import tornado.web-from marimo._server import sessions+from marimo._server.api.validated_handler import ValidatedHandler-class InterruptHandler(tornado.web.RequestHandler):+class InterruptHandler(ValidatedHandler):"""Interrupt the kernel's execution."""def post(self) -> None:diff --git a/marimo/_server/api/rename.py b/marimo/_server/api/rename.pyindex 2f7be7efc2..f3d9716c8b 100644--- a/marimo/_server/api/rename.py+++ b/marimo/_server/api/rename.py@@ -9,6 +9,7 @@ import tornado.webfrom marimo import _loggersfrom marimo._server import sessionsfrom marimo._server.api import status+from marimo._server.api.validated_handler import ValidatedHandlerfrom marimo._server.utils import canonicalize_filenamefrom marimo._utils.parse_dataclass import parse_raw@@ -20,7 +21,7 @@ class Rename:filename: str-class RenameHandler(tornado.web.RequestHandler):+class RenameHandler(ValidatedHandler):"""Rename the current app."""@sessions.requires_editdiff --git a/marimo/_server/api/run.py b/marimo/_server/api/run.pyindex dbd799ee02..29b87d4c89 100644--- a/marimo/_server/api/run.py+++ b/marimo/_server/api/run.py@@ -4,11 +4,10 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import List-import tornado.web-from marimo._ast.cell import CellId_tfrom marimo._runtime import requestsfrom marimo._server import sessions+from marimo._server.api.validated_handler import ValidatedHandlerfrom marimo._utils.parse_dataclass import parse_raw@@ -20,7 +19,7 @@ class Run:codes: List[str]-class RunHandler(tornado.web.RequestHandler):+class RunHandler(ValidatedHandler):"""Run multiple cells (and their descendants).Only allowed in edit mode.diff --git a/marimo/_server/api/save.py b/marimo/_server/api/save.pyindex 6f705c029b..9701029312 100644--- a/marimo/_server/api/save.py+++ b/marimo/_server/api/save.py@@ -12,6 +12,7 @@ from marimo._ast import codegenfrom marimo._ast.cell import CellConfigfrom marimo._server import sessionsfrom marimo._server.api.status import HTTPStatus+from marimo._server.api.validated_handler import ValidatedHandlerfrom marimo._server.layout import LayoutConfig, save_layout_configfrom marimo._server.utils import canonicalize_filenamefrom marimo._utils.parse_dataclass import parse_raw@@ -33,7 +34,7 @@ class Save:layout: Optional[Dict[str, Any]] = None-class SaveHandler(tornado.web.RequestHandler):+class SaveHandler(ValidatedHandler):"""Save an app to disk."""@sessions.requires_editdiff --git a/marimo/_server/api/save_app_config.py b/marimo/_server/api/save_app_config.pyindex 6ede662f42..70bc262e52 100644--- a/marimo/_server/api/save_app_config.py+++ b/marimo/_server/api/save_app_config.py@@ -10,6 +10,7 @@ from marimo import _loggersfrom marimo._ast import codegenfrom marimo._server import sessionsfrom marimo._server.api.status import HTTPStatus+from marimo._server.api.validated_handler import ValidatedHandlerfrom marimo._utils.parse_dataclass import parse_rawLOGGER = _loggers.marimo_logger()@@ -21,7 +22,7 @@ class SaveAppConfiguration:config: Dict[str, Any]-class SaveAppConfigurationHandler(tornado.web.RequestHandler):+class SaveAppConfigurationHandler(ValidatedHandler):"""Save app configuration to session manager."""@sessions.requires_editdiff --git a/marimo/_server/api/save_user_config.py b/marimo/_server/api/save_user_config.pyindex af6c9bd7a3..7128626db4 100644--- a/marimo/_server/api/save_user_config.py+++ b/marimo/_server/api/save_user_config.py@@ -14,6 +14,7 @@ from marimo._config.utils import get_config_pathfrom marimo._runtime import requestsfrom marimo._server import sessionsfrom marimo._server.api.status import HTTPStatus+from marimo._server.api.validated_handler import ValidatedHandlerfrom marimo._utils.parse_dataclass import parse_rawLOGGER = _loggers.marimo_logger()@@ -44,7 +45,7 @@ class SaveUserConfiguration:config: MarimoConfig-class SaveUserConfigurationHandler(tornado.web.RequestHandler):+class SaveUserConfigurationHandler(ValidatedHandler):"""Save user configuration to disk."""@sessions.requires_editdiff --git a/marimo/_server/api/set_cell_config.py b/marimo/_server/api/set_cell_config.pyindex 241f366664..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 annotationsfrom dataclasses import dataclassfrom typing import Dict-import tornado.web-from marimo._ast.cell import CellId_tfrom marimo._runtime import requestsfrom marimo._server import sessions+from marimo._server.api.validated_handler import ValidatedHandlerfrom marimo._utils.parse_dataclass import parse_raw@@ -18,7 +17,7 @@ class SetCellConfig:configs: Dict[CellId_t, Dict[str, object]]-class SetCellConfigHandler(tornado.web.RequestHandler):+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.pyindex 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 annotationsfrom dataclasses import dataclassfrom typing import Any, List-import tornado.web-from marimo._runtime import requestsfrom marimo._server import sessions+from marimo._server.api.validated_handler import ValidatedHandlerfrom 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/validated_handler.py b/marimo/_server/api/validated_handler.pynew file mode 100644index 0000000000..90f80f44c0--- /dev/null+++ b/marimo/_server/api/validated_handler.py@@ -0,0 +1,13 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++import tornado.web++from marimo._server import sessions+++class ValidatedHandler(tornado.web.RequestHandler):+ def prepare(self) -> None:+ # Validate the server token -- don't allow connections from frontends+ # that weren't generated by this server+ sessions.check_server_token(self.request.headers)diff --git a/marimo/_server/api/virtual_file.py b/marimo/_server/api/virtual_file.pyindex 91857fb051..139e1386a6 100644--- a/marimo/_server/api/virtual_file.py+++ b/marimo/_server/api/virtual_file.py@@ -7,9 +7,7 @@ from multiprocessing import shared_memoryimport tornado.webfrom marimo import _loggers-from marimo._runtime.virtual_file import (- EMPTY_VIRTUAL_FILE,-)+from marimo._runtime.virtual_file import EMPTY_VIRTUAL_FILEfrom marimo._server.api.status import HTTPStatusLOGGER = _loggers.marimo_logger()diff --git a/marimo/_server/server.py b/marimo/_server/server.pyindex c7a3a554f1..8cb9fbb49c 100644--- a/marimo/_server/server.py+++ b/marimo/_server/server.py@@ -125,6 +125,7 @@ class MainHandler(tornado.web.RequestHandler):version=__version__,user_config=json.dumps(user_config),app_config=json.dumps(app_config),+ server_token=mgr.server_token,)diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 54cabf0048..12acbe2981 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -27,6 +27,7 @@ import threadingfrom enum import Enumfrom multiprocessing import connectionfrom typing import Any, Callable, Optional+from uuid import uuid4import importlib_resourcesimport tornado.httputil@@ -377,6 +378,7 @@ class SessionManager:The SessionManager also encapsulates state common to all sessions:- the app filename- the app mode (edit or run)+ - the server token"""def __init__(@@ -396,6 +398,8 @@ class SessionManager:self.quiet = quietself.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@@ -558,6 +562,35 @@ def get_manager() -> SessionManager:return SESSION_MANAGER+def server_token_from_header(+ headers: tornado.httputil.HTTPHeaders,+) -> str:+ """Extracts session ID from request header.++ All endpoints require a session ID to be in the request header.+ """+ server_token = headers.get_list("Marimo-Server-Token")+ if not server_token:+ raise RuntimeError(+ "Invalid headers (Marimo-Server-Token not found)\n\n"+ + str(headers)+ )+ elif len(server_token) > 1:+ raise RuntimeError(+ "Invalid headers (> 1 Marimo-Server-Token)\n\n" + str(headers)+ )+ return server_token[0]+++def check_server_token(headers: tornado.httputil.HTTPHeaders) -> None:+ """Throws an HTTPError if no Session is found."""+ server_token = server_token_from_header(headers)+ if server_token != get_manager().server_token:+ raise tornado.web.HTTPError(+ HTTPStatus.FORBIDDEN, "Inavlid server token."+ )++def session_id_from_header(headers: tornado.httputil.HTTPHeaders,) -> str:@@ -568,11 +601,11 @@ def session_id_from_header(session_id = headers.get_list("Marimo-Session-Id")if not session_id:raise RuntimeError(- "Invalid headers (Marimo-Session-Id not found\n\n)" + str(headers)+ "Invalid headers (Marimo-Session-Id not found)\n\n" + str(headers))elif len(session_id) > 1:raise RuntimeError(- "Invalid headers (> 1 Marimo-Session-Id\n\n)" + str(headers)+ "Invalid headers (> 1 Marimo-Session-Id)\n\n" + str(headers))return session_id[0]