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
Merge commit from fork
Dylan Madisettib2f7e9bcfa3e
diff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.pyindex 757f03832c..95ec81edd1 100644--- a/marimo/_server/templates/templates.py+++ b/marimo/_server/templates/templates.py@@ -24,11 +24,24 @@ from marimo._version import __version__MOUNT_CONFIG_TEMPLATE = "'{{ mount_config }}'"+_json_script_escapes = {+ ord(">"): "\\u003E",+ ord("<"): "\\u003C",+ ord("&"): "\\u0026",+}++def _html_escape(text: str) -> str:"""Escape HTML special characters."""return html.escape(text, quote=True)+def json_script(data: Any) -> str:+ # See https://github.com/django/django/blob/main/django/utils/html.py#L88C1-L92C2+ # Only escape values that can break out of a script tag+ return json.dumps(data, sort_keys=True).translate(_json_script_escapes)++def _get_mount_config(*,filename: Optional[str],@@ -79,7 +92,7 @@ def _get_mount_config("runtimeConfig": {runtime_config},}}""".format(- **{k: json.dumps(v, sort_keys=True) for k, v in options.items()}+ **{k: json_script(v) for k, v in options.items()}).strip()@@ -258,7 +271,7 @@ def static_notebook_template(f"""<script data-marimo="true">window.__MARIMO_STATIC__ = {{}};- window.__MARIMO_STATIC__.files = {json.dumps(files)};+ window.__MARIMO_STATIC__.files = {json_script(files)};</script>""")diff --git a/tests/_server/templates/test_templates.py b/tests/_server/templates/test_templates.pyindex 146789d0fe..b11136f1b3 100644--- a/tests/_server/templates/test_templates.py+++ b/tests/_server/templates/test_templates.py@@ -701,6 +701,119 @@ class TestStaticNotebookTemplate(unittest.TestCase):assert "<style title='marimo-custom'>" not in result_assert_no_leftover_replacements(result)+ def test_static_files_injection_prevention(self) -> None:+ """Test that malicious content in files dict doesn't enable script breakout."""+ # Test with malicious file keys and values+ malicious_files = {+ "normal.txt": "safe content",+ "</script><script>alert(1)</script>": "content",+ "file.js": "</script><img src=x onerror=alert(1)>",+ "test&<>.py": "content with <script>alert(1)</script>",+ }++ result = templates.static_notebook_template(+ self.html,+ self.user_config,+ self.config_overrides,+ self.server_token,+ self.app_config,+ self.filepath,+ self.code,+ hash_code(self.code),+ self.session_snapshot,+ self.notebook_snapshot,+ malicious_files,+ )++ # Must not contain unescaped script breakout sequences (< and > escaped)+ assert "</script><script>alert(1)" not in result+ assert "<img" not in result # The < should be escaped++ # Must contain escaped versions of < and >+ assert "\\u003C" in result or "\\u003E" in result++ # Must still be valid HTML+ _assert_no_leftover_replacements(result)++ def test_static_malicious_filename_injection(self) -> None:+ """Test that malicious filenames in static exports are properly escaped."""+ malicious_filepath = self.tmp_path / "</script><script>alert(1)</script>.py"++ result = templates.static_notebook_template(+ self.html,+ self.user_config,+ self.config_overrides,+ self.server_token,+ self.app_config,+ str(malicious_filepath),+ self.code,+ hash_code(self.code),+ self.session_snapshot,+ self.notebook_snapshot,+ self.files,+ )++ # Must not contain unescaped script tags+ assert "</script><script>" not in result+ assert "<script>alert(1)" not in result.replace("\\u003Cscript\\u003E", "")++ # Must contain escaped versions in JSON context+ assert "\\u003C" in result or "\\u003E" in result++ _assert_no_leftover_replacements(result)++ def test_static_malicious_code_content(self) -> None:+ """Test that malicious code content is properly escaped in static export."""+ malicious_code = """+import marimo as mo+# This code contains </script><script>alert('XSS')</script>+mo.md("<img src=x onerror=alert(1)>")+"""++ # Create session with malicious code in output+ malicious_session = NotebookSessionV1(+ version=VERSION,+ metadata=NotebookSessionMetadata(marimo_version="0.1.0"),+ cells=[+ Cell(+ cell_id="cell1",+ code=malicious_code,+ outputs=[+ DataOutput(+ channel="output",+ mimetype="text/html",+ data="</script><script>alert(1)</script>",+ timestamp=0.0,+ )+ ],+ console=[],+ )+ ],+ )++ result = templates.static_notebook_template(+ self.html,+ self.user_config,+ self.config_overrides,+ self.server_token,+ self.app_config,+ self.filepath,+ malicious_code,+ hash_code(malicious_code),+ malicious_session,+ self.notebook_snapshot,+ self.files,+ )++ # The malicious code itself should be in JSON context (escaped)+ # Must not have unescaped dangerous sequences in script tags (< and > escaped)+ assert "</script><script>alert('XSS')" not in result++ # Must have escaped versions of < and >+ assert "\\u003C" in result or "\\u003E" in result++ _assert_no_leftover_replacements(result)+class TestWasmNotebookTemplate(unittest.TestCase):def setUp(self) -> None:diff --git a/tests/_server/test_templates_filename.py b/tests/_server/test_templates_filename.pyindex a13f15a494..449ad3aae9 100644--- a/tests/_server/test_templates_filename.py+++ b/tests/_server/test_templates_filename.py@@ -10,6 +10,7 @@ from marimo._config.config import MarimoConfig, PartialMarimoConfigfrom marimo._server.templates.templates import (_get_mount_config,_html_escape,+ json_script,)from marimo._server.tokens import SkewProtectionTokenfrom tests.mocks import EDGE_CASE_FILENAMES@@ -85,3 +86,258 @@ class TestTemplateFilenameHandling:# Filename should be properly handledexpected_filename = filename or ""assert config_data["filename"] == expected_filename+++class TestJsonScriptEscaping:+ """Test json_script() function for script tag breakout prevention."""++ @pytest.mark.parametrize(+ "payload",+ [+ # Script tag breakout attempts+ "</script><script>alert('XSS')</script>",+ "<script>alert(1)</script>",+ "</script><img src=x onerror=alert(1)>",+ "<img src=x onerror=alert(1)>",+ # JavaScript string breakout attempts+ "'; alert(1); //",+ '"; alert(1); //',+ # Raw script tags+ "</script>",+ "<script>",+ # Combinations+ ">&<",+ "</SCRIPT><SCRIPT>alert(1)</SCRIPT>",+ # With valid content mixed in+ "normal text</script><script>alert(1)</script>more text",+ ],+ )+ def test_script_breakout_prevention(self, payload: str) -> None:+ """Verify dangerous characters are escaped to prevent script tag breakout."""+ result = json_script({"malicious": payload})++ # Must not contain literal < or > that could break out of script tag+ # Note: json_script only escapes <, >, & - other strings are safe in JSON context+ assert "<script>" not in result.lower()+ assert "</script>" not in result.lower()++ # Must contain escaped versions of dangerous chars+ # json_script escapes <, >, & to \uXXXX format+ if "<" in payload or ">" in payload or "&" in payload:+ assert "\\u003C" in result or "\\u003E" in result or "\\u0026" in result++ # Must be valid JSON that round-trips correctly+ parsed = json.loads(result)+ assert parsed["malicious"] == payload++ @pytest.mark.parametrize(+ ("data", "must_not_contain"),+ [+ # Nested structures with malicious content+ (+ {"nested": {"deep": "</script><script>alert(1)</script>"}},+ ["</script>", "<script>"],+ ),+ # Arrays with malicious content+ (+ {"items": ["</script>", "<script>", "&"]},+ ["</script>", "<script>"],+ ),+ # Multiple fields with different injection attempts+ (+ {+ "field1": "</script>",+ "field2": "<img src=x onerror=alert(1)>",+ "field3": "normal & text",+ },+ ["</script>", "<img"],+ ),+ ],+ )+ def test_complex_structure_escaping(+ self, data: dict, must_not_contain: list[str]+ ) -> None:+ """Verify json_script escapes dangerous chars in complex nested structures."""+ result = json_script(data)++ # Must not contain any unescaped dangerous sequences+ for dangerous in must_not_contain:+ assert dangerous not in result++ # Must be valid JSON that round-trips correctly+ parsed = json.loads(result)+ assert parsed == data++ @pytest.mark.parametrize(+ "data",+ [+ # Unicode characters+ {"text": "café"},+ {"text": "测试"},+ {"text": "🚀"},+ # Unicode mixed with dangerous characters+ {"text": "café</script>"},+ {"text": "测试<script>alert(1)</script>"},+ # Combining characters+ {"text": "e\u0301"}, # é as combining character+ # Right-to-left marks+ {"text": "\u200F"},+ # Zero-width characters+ {"text": "test\u200Bword"},+ ],+ )+ def test_unicode_handling(self, data: dict) -> None:+ """Verify unicode characters are handled correctly without bypassing escaping."""+ result = json_script(data)++ # Must not contain unescaped dangerous sequences+ assert "</script>" not in result+ assert "<script>" not in result++ # Must be valid JSON that preserves unicode+ parsed = json.loads(result)+ assert parsed == data++ def test_json_validity_after_escaping(self) -> None:+ """Verify json_script produces valid JSON that JavaScript can parse."""+ test_data = {+ "string": "test</script>",+ "number": 42,+ "float": 3.14,+ "bool": True,+ "null": None,+ "array": [1, 2, 3],+ "nested": {"key": "value<script>"},+ }++ result = json_script(test_data)++ # Must be valid JSON+ parsed = json.loads(result)+ assert parsed == test_data++ # Must maintain sort_keys=True behavior+ keys_order = list(parsed.keys())+ assert keys_order == sorted(keys_order)++ @pytest.mark.parametrize(+ "xss_payload",+ [+ # OWASP XSS cheat sheet payloads+ "<svg/onload=alert(1)>",+ "<iframe src=javascript:alert(1)>",+ "<object data=javascript:alert(1)>",+ "<embed src=javascript:alert(1)>",+ "<body onload=alert(1)>",+ "javascript:alert(1)",+ "data:text/html,<script>alert(1)</script>",+ # PortSwigger XSS payloads+ "<img src=x onerror=alert(document.domain)>",+ "<svg><script>alert(1)</script></svg>",+ # Encoded variations+ "</script><script>alert(String.fromCharCode(88,83,83))</script>",+ # Case variations+ "</ScRiPt><ScRiPt>alert(1)</ScRiPt>",+ ],+ )+ def test_real_world_xss_payloads(self, xss_payload: str) -> None:+ """Test json_script against real-world XSS attack payloads."""+ result = json_script({"payload": xss_payload})++ # Must not contain unescaped < or > that could break out of script tags+ # json_script specifically prevents script tag breakout by escaping <, >, &+ assert "<script" not in result.lower()++ # Must escape dangerous characters < and >+ if "<" in xss_payload or ">" in xss_payload:+ assert "\\u003C" in result or "\\u003E" in result++ # Must be valid JSON+ parsed = json.loads(result)+ assert parsed["payload"] == xss_payload+++class TestMountConfigInjectionPrevention:+ """Test _get_mount_config prevents injection attacks in all fields."""++ @pytest.mark.parametrize(+ "malicious_filename",+ [+ "</script><script>alert('XSS')</script>.py",+ "<script>alert(1)</script>.py",+ "test</script>.py",+ "<img src=x onerror=alert(1)>.py",+ ],+ )+ def test_filename_injection_prevention(+ self, malicious_filename: str+ ) -> None:+ """Test that malicious filenames don't enable script breakout in mount config."""+ server_token = SkewProtectionToken("test-token")+ user_config = MarimoConfig()+ config_overrides = PartialMarimoConfig()+ app_config = _AppConfig()++ result = _get_mount_config(+ filename=malicious_filename,+ mode="edit",+ server_token=server_token,+ user_config=user_config,+ config_overrides=config_overrides,+ app_config=app_config,+ )++ # Remove trailing comma for JSON parsing+ last_comma_index = result.rfind(",")+ result = result[:last_comma_index] + result[last_comma_index + 1 :]++ # Must not contain unescaped script tags (< and > should be escaped)+ assert "</script><script>" not in result+ assert "<script>" not in result.lower()++ # Must be valid JSON+ config_data = json.loads(result)+ assert config_data["filename"] == malicious_filename++ # Verify the actual output contains escaped versions of < and >+ assert "\\u003C" in result or "\\u003E" in result++ @pytest.mark.parametrize(+ "malicious_title",+ [+ "</script><script>alert(1)</script>",+ "<img src=x onerror=alert(1)>",+ "normal title</script>",+ ],+ )+ def test_app_title_injection_prevention(+ self, malicious_title: str+ ) -> None:+ """Test that malicious app titles don't enable script breakout."""+ server_token = SkewProtectionToken("test-token")+ user_config = MarimoConfig()+ config_overrides = PartialMarimoConfig()+ app_config = _AppConfig(app_title=malicious_title)++ result = _get_mount_config(+ filename="test.py",+ mode="edit",+ server_token=server_token,+ user_config=user_config,+ config_overrides=config_overrides,+ app_config=app_config,+ )++ # Remove trailing comma+ last_comma_index = result.rfind(",")+ result = result[:last_comma_index] + result[last_comma_index + 1 :]++ # Must not contain unescaped script tags (< and > should be escaped)+ assert "</script><script>" not in result++ # Must be valid JSON+ config_data = json.loads(result)++ # Verify escaping in output (< and > are escaped)+ if "<" in malicious_title or ">" in malicious_title:+ assert "\\u003C" in result or "\\u003E" in result