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: sanitize stdout and stderr (#1297)
Myles Scolnickd79858e79b23
diff --git a/frontend/src/components/editor/Output.tsx b/frontend/src/components/editor/Output.tsxindex 3b867019d2..efd76223a1 100644--- a/frontend/src/components/editor/Output.tsx+++ b/frontend/src/components/editor/Output.tsx@@ -47,9 +47,6 @@ export const OutputRenderer: React.FC<{return <HtmlOutput className={channel} html={message.data} />;case "text/plain":- if (message.data.includes(`class="codehilite"`)) {- return <HtmlOutput className={channel} html={message.data} />;- }return <TextOutput channel={channel} text={message.data} />;case "application/json":diff --git a/frontend/src/components/editor/output/__tests__/ansi.test.ts b/frontend/src/components/editor/output/__tests__/ansi.test.tsnew file mode 100644index 0000000000..733b7bb3aa--- /dev/null+++ b/frontend/src/components/editor/output/__tests__/ansi.test.ts@@ -0,0 +1,39 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { AnsiUp } from "ansi_up";+import { describe, expect, test } from "vitest";++const ansiUp = new AnsiUp();++describe("ansi", () => {+ test("basic", () => {+ const text = "string";+ const value = ansiUp.ansi_to_html(text);+ expect(value).toMatchInlineSnapshot(`"string"`);+ });++ test("with ansi", () => {+ const text = "'\u001B[30mblack\u001B[37mwhite'";+ const value = ansiUp.ansi_to_html(text);+ expect(value).toMatchInlineSnapshot(+ `"'<span style="color:rgb(0,0,0)">black</span><span style="color:rgb(255,255,255)">white'</span>"`,+ );+ });++ test("with html", () => {+ // HTML gets escaped+ const text = "<b>string</b>";+ const value = ansiUp.ansi_to_html(text);+ expect(value).toMatchInlineSnapshot(+ `"<span style="color:rgb(255,255,255)"><b>string</b></span>"`,+ );+ });++ test("with ansi and html", () => {+ // HTML gets escaped+ const text = "'\u001B[1m<b>string\u001B[0m</b>'";+ const value = ansiUp.ansi_to_html(text);+ expect(value).toMatchInlineSnapshot(+ `"<span style="color:rgb(255,255,255)">'</span><span style="font-weight:bold;color:rgb(255,255,255)"><b>string</span></b>'"`,+ );+ });+});diff --git a/frontend/src/plugins/core/__test__/RenderHTML.test.ts b/frontend/src/plugins/core/__test__/RenderHTML.test.tsindex 9d7cea5c95..132e2fad88 100644--- a/frontend/src/plugins/core/__test__/RenderHTML.test.ts+++ b/frontend/src/plugins/core/__test__/RenderHTML.test.ts@@ -101,3 +101,25 @@ describe("RenderHTML", () => {`);});});++describe("RenderHTML with < nad >", () => {+ const html =+ 'thread <unnamed> panicked at "assertion failed: `(left == right)`"';+ test("<unnamed>", () => {+ expect(renderHTML({ html })).toMatchInlineSnapshot(`+ [+ "thread ",+ <unnamed>+ panicked at "assertion failed: \`(left == right)\`"+ </unnamed>,+ ]+ `);+ });++ test("<unnamed> sanitized", () => {+ const sanitized = html.replaceAll("<", "<").replaceAll(">", ">");+ expect(renderHTML({ html: sanitized })).toMatchInlineSnapshot(+ `"thread <unnamed> panicked at "assertion failed: \`(left == right)\`""`,+ );+ });+});diff --git a/marimo/_messaging/cell_output.py b/marimo/_messaging/cell_output.pyindex 71cce7adc6..d52aa6dc0e 100644--- a/marimo/_messaging/cell_output.py+++ b/marimo/_messaging/cell_output.py@@ -40,13 +40,17 @@ class CellOutput:@staticmethoddef stdout(data: str) -> CellOutput:return CellOutput(- channel=CellChannel.STDOUT, mimetype="text/plain", data=data+ channel=CellChannel.STDOUT,+ mimetype="text/plain",+ data=data,)@staticmethoddef stderr(data: str) -> CellOutput:return CellOutput(- channel=CellChannel.STDERR, mimetype="text/plain", data=data+ channel=CellChannel.STDERR,+ mimetype="text/plain",+ data=data,)@staticmethoddiff --git a/marimo/_messaging/console_output_worker.py b/marimo/_messaging/console_output_worker.pyindex 39431b5fc3..b03e0d6737 100644--- a/marimo/_messaging/console_output_worker.py+++ b/marimo/_messaging/console_output_worker.py@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Literalfrom marimo._ast.cell import CellId_tfrom marimo._messaging.cell_output import CellChannel, CellOutput+from marimo._messaging.mimetypes import KnownMimeTypeif TYPE_CHECKING:from collections import deque@@ -26,6 +27,7 @@ class ConsoleMsg:stream: StreamTcell_id: CellId_tdata: str+ mimetype: KnownMimeTypedef _write_console_output(@@ -33,6 +35,7 @@ def _write_console_output(stream_type: StreamT,cell_id: CellId_t,data: str,+ mimetype: KnownMimeType,) -> None:from marimo._messaging.ops import CellOp@@ -40,7 +43,7 @@ def _write_console_output(cell_id=cell_id,console=CellOutput(channel=stream_type,- mimetype="text/plain",+ mimetype=mimetype,data=data,),).broadcast(stream)@@ -109,7 +112,11 @@ def buffered_writer(for cell_id, buffer in outputs_buffered_per_cell.items():for output in buffer:_write_console_output(- stream, output.stream, cell_id, output.data+ stream,+ output.stream,+ cell_id,+ output.data,+ output.mimetype,)outputs_buffered_per_cell = {}timer = Nonediff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.pyindex 01b36e1b33..a9c15f54e0 100644--- a/marimo/_messaging/streams.py+++ b/marimo/_messaging/streams.py@@ -13,6 +13,7 @@ from marimo import _loggersfrom marimo._ast.cell import CellId_tfrom marimo._messaging.cell_output import CellChannelfrom marimo._messaging.console_output_worker import ConsoleMsg, buffered_writer+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._messaging.types import (KernelMessage,Stderr,@@ -178,7 +179,7 @@ class ThreadSafeStdout(Stdout):# TODO(akshayka): maybe force the buffered writer to writereturn- def write(self, data: str) -> int:+ def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:assert self._stream.cell_id is not Noneif not isinstance(data, str):raise TypeError(@@ -194,6 +195,7 @@ class ThreadSafeStdout(Stdout):stream=CellChannel.STDOUT,cell_id=self._stream.cell_id,data=data,+ mimetype=mimetype,))with self._stream.console_msg_cv:@@ -237,7 +239,7 @@ class ThreadSafeStderr(Stderr):# TODO(akshayka): maybe force the buffered writer to writereturn- def write(self, data: str) -> int:+ def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:assert self._stream.cell_id is not Noneif not isinstance(data, str):raise TypeError(@@ -256,6 +258,7 @@ class ThreadSafeStderr(Stderr):stream=CellChannel.STDERR,cell_id=self._stream.cell_id,data=data,+ mimetype=mimetype,))self._stream.console_msg_cv.notify()@@ -307,6 +310,7 @@ class ThreadSafeStdin(Stdin):stream=CellChannel.STDIN,cell_id=self._stream.cell_id,data=prompt,+ mimetype="text/plain",))self._stream.console_msg_cv.notify()diff --git a/marimo/_messaging/tracebacks.py b/marimo/_messaging/tracebacks.pyindex f7465c5cc4..76c670ec05 100644--- a/marimo/_messaging/tracebacks.py+++ b/marimo/_messaging/tracebacks.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport sys-from marimo._runtime.context.types import ContextNotInitializedError+from marimo._messaging.types import Stderrdef _highlight_traceback(traceback: str) -> str:@@ -22,14 +22,13 @@ def _highlight_traceback(traceback: str) -> str:def write_traceback(traceback: str) -> None:- from marimo._runtime.context import get_context-- try:- ctx = get_context()- except ContextNotInitializedError:- ctx = None-- if ctx is not None and ctx.stderr is not None:- sys.stderr.write(_highlight_traceback(traceback))+ if isinstance(sys.stderr, Stderr):+ sys.stderr._write_with_mimetype(+ _highlight_traceback(traceback), mimetype="text/html"+ )else:sys.stderr.write(traceback)+++def is_code_highlighting(value: str) -> bool:+ return 'class="codehilite"' in valuediff --git a/marimo/_messaging/types.py b/marimo/_messaging/types.pyindex 7955edff9d..2758d32a5f 100644--- a/marimo/_messaging/types.py+++ b/marimo/_messaging/types.py@@ -4,6 +4,7 @@ import iofrom typing import Any, Dict, Optional, Tuplefrom marimo._ast.cell import CellId_t+from marimo._messaging.mimetypes import KnownMimeType# The message from the kernel is a tuple of message type# and a json representation of the message@@ -33,17 +34,23 @@ class Stdout(io.TextIOBase):name = "stdout"@abc.abstractmethod- def write(self, __s: str) -> int:+ def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:pass+ def write(self, __s: str) -> int:+ return self._write_with_mimetype(__s, mimetype="text/plain")+class Stderr(io.TextIOBase):name = "stderr"@abc.abstractmethod- def write(self, __s: str) -> int:+ def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:pass+ def write(self, __s: str) -> int:+ return self._write_with_mimetype(__s, mimetype="text/plain")+class Stdin(io.TextIOBase):name = "stdin"diff --git a/marimo/_pyodide/streams.py b/marimo/_pyodide/streams.pyindex 4265ec356e..6327362629 100644--- a/marimo/_pyodide/streams.py+++ b/marimo/_pyodide/streams.py@@ -8,6 +8,7 @@ from typing import Any, Callable, Iterable, Optionalfrom marimo import _loggersfrom marimo._ast.cell import CellId_tfrom marimo._messaging.cell_output import CellChannel, CellOutput+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._messaging.ops import CellOpfrom marimo._messaging.streams import STD_STREAM_MAX_BYTESfrom marimo._messaging.types import (@@ -55,7 +56,7 @@ class PyodideStdout(Stdout):def seekable(self) -> bool:return False- def write(self, data: str) -> int:+ def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:assert self.stream.cell_id is not Noneif not isinstance(data, str):raise TypeError(@@ -70,7 +71,7 @@ class PyodideStdout(Stdout):cell_id=self.stream.cell_id,console=CellOutput(channel=CellChannel.STDOUT,- mimetype="text/plain",+ mimetype=mimetype,data=data,),).broadcast(self.stream)@@ -99,7 +100,7 @@ class PyodideStderr(Stderr):def seekable(self) -> bool:return False- def write(self, data: str) -> int:+ def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:assert self.stream.cell_id is not Noneif not isinstance(data, str):raise TypeError(@@ -116,7 +117,7 @@ class PyodideStderr(Stderr):cell_id=self.stream.cell_id,console=CellOutput(channel=CellChannel.STDERR,- mimetype="text/plain",+ mimetype=mimetype,data=data,),).broadcast(self.stream)diff --git a/marimo/_runtime/output/_output.py b/marimo/_runtime/output/_output.pyindex 7d8f6fc733..e3d3c172a6 100644--- a/marimo/_runtime/output/_output.py+++ b/marimo/_runtime/output/_output.py@@ -1,9 +1,9 @@# Copyright 2024 Marimo. All rights reserved.-import sysfrom marimo._ast.cell import CellId_tfrom marimo._messaging.cell_output import CellChannelfrom marimo._messaging.ops import CellOp+from marimo._messaging.tracebacks import write_tracebackfrom marimo._output import formattingfrom marimo._output.rich_help import mddocfrom marimo._plugins.stateless.flex import vstack@@ -13,7 +13,7 @@ from marimo._runtime.context import get_contextdef write_internal(cell_id: CellId_t, value: object) -> None:output = formatting.try_format(value)if output.traceback is not None:- sys.stderr.write(output.traceback)+ write_traceback(output.traceback)CellOp.broadcast_output(channel=CellChannel.OUTPUT,mimetype=output.mimetype,diff --git a/marimo/_smoke_tests/bugs/1270.py b/marimo/_smoke_tests/bugs/1270.pynew file mode 100644index 0000000000..deede3922e--- /dev/null+++ b/marimo/_smoke_tests/bugs/1270.py@@ -0,0 +1,18 @@+# Copyright 2024 Marimo. All rights reserved.+import marimo++__generated_with = "0.4.10"+app = marimo.App()+++def __():+ import marimo as mo+ import polars as pl++ pl.DataFrame(data=[{'num': [1], 'x': [2]}]).group_by('num').map_groups(lambda x: pl.DataFrame(data=123))+ return mo, pl+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_smoke_tests/bugs/1273.py b/marimo/_smoke_tests/bugs/1273.pyindex 22946df4ba..efbae1e0ff 100644--- a/marimo/_smoke_tests/bugs/1273.py+++ b/marimo/_smoke_tests/bugs/1273.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import marimo__generated_with = "0.4.7"diff --git a/marimo/_smoke_tests/bugs/1279.py b/marimo/_smoke_tests/bugs/1279.pyindex ab956adc0d..35f2976cb7 100644--- a/marimo/_smoke_tests/bugs/1279.py+++ b/marimo/_smoke_tests/bugs/1279.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import marimo__generated_with = "0.4.7"diff --git a/marimo/_smoke_tests/bugs/1291.py b/marimo/_smoke_tests/bugs/1291.pyindex 8a826d86f3..931ec7d3fd 100644--- a/marimo/_smoke_tests/bugs/1291.py+++ b/marimo/_smoke_tests/bugs/1291.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import marimo__generated_with = "0.4.9"diff --git a/tests/_runtime/test_cell_runner.py b/tests/_runtime/test_cell_runner.pyindex b1ec11eff3..eee21c375e 100644--- a/tests/_runtime/test_cell_runner.py+++ b/tests/_runtime/test_cell_runner.py@@ -46,8 +46,7 @@ async def test_traceback_includes_lineno()with capture_stderr() as buffer:await runner.run(er.cell_id)- # pygments inserts HTML in traceback- assert 'line <span class="m">3</span>' in buffer.getvalue()+ assert "line 3" in buffer.getvalue()async def test_base_exception_caught(@@ -78,5 +77,4 @@ async def test_base_exception_caught()with capture_stderr() as buffer:await runner.run(er.cell_id)- # pygments inserts HTML in traceback- assert 'line <span class="m">3</span>' in buffer.getvalue()+ assert "line 3" in buffer.getvalue()diff --git a/tests/conftest.py b/tests/conftest.pyindex a75e5804fe..354d684d51 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -13,6 +13,7 @@ import pytestfrom marimo._ast.app import CellManagerfrom marimo._ast.cell import CellId_tfrom marimo._config.config import DEFAULT_CONFIG+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._messaging.streams import (ThreadSafeStderr,ThreadSafeStdin,@@ -45,7 +46,8 @@ class MockStdout(ThreadSafeStdout):super().__init__(stream)self.messages: list[str] = []- def write(self, data: str) -> int:+ def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:+ del mimetypeself.messages.append(data)return len(data)@@ -59,7 +61,8 @@ class MockStderr(ThreadSafeStderr):super().__init__(stream)self.messages: list[str] = []- def write(self, data: str) -> int:+ def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:+ del mimetypeself.messages.append(data)return len(data)