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: sanitize stdout and stderr (#1297)

Myles Scolnickd79858e79b23
diff --git a/frontend/src/components/editor/Output.tsx b/frontend/src/components/editor/Output.tsx
index 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.ts
new file mode 100644
index 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(
+ `"&#x27;<span style="color:rgb(0,0,0)">black</span><span style="color:rgb(255,255,255)">white&#x27;</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)">&lt;b&gt;string&lt;/b&gt;</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)">&#x27;</span><span style="font-weight:bold;color:rgb(255,255,255)">&lt;b&gt;string</span>&lt;/b&gt;&#x27;"`,
+ );
+ });
+});
diff --git a/frontend/src/plugins/core/__test__/RenderHTML.test.ts b/frontend/src/plugins/core/__test__/RenderHTML.test.ts
index 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("<", "&lt;").replaceAll(">", "&gt;");
+ 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.py
index 71cce7adc6..d52aa6dc0e 100644
--- a/marimo/_messaging/cell_output.py
+++ b/marimo/_messaging/cell_output.py
@@ -40,13 +40,17 @@ class CellOutput:
@staticmethod
def stdout(data: str) -> CellOutput:
return CellOutput(
- channel=CellChannel.STDOUT, mimetype="text/plain", data=data
+ channel=CellChannel.STDOUT,
+ mimetype="text/plain",
+ data=data,
)
@staticmethod
def stderr(data: str) -> CellOutput:
return CellOutput(
- channel=CellChannel.STDERR, mimetype="text/plain", data=data
+ channel=CellChannel.STDERR,
+ mimetype="text/plain",
+ data=data,
)
@staticmethod
diff --git a/marimo/_messaging/console_output_worker.py b/marimo/_messaging/console_output_worker.py
index 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, Literal
from marimo._ast.cell import CellId_t
from marimo._messaging.cell_output import CellChannel, CellOutput
+from marimo._messaging.mimetypes import KnownMimeType
if TYPE_CHECKING:
from collections import deque
@@ -26,6 +27,7 @@ class ConsoleMsg:
stream: StreamT
cell_id: CellId_t
data: str
+ mimetype: KnownMimeType
def _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 = None
diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.py
index 01b36e1b33..a9c15f54e0 100644
--- a/marimo/_messaging/streams.py
+++ b/marimo/_messaging/streams.py
@@ -13,6 +13,7 @@ from marimo import _loggers
from marimo._ast.cell import CellId_t
from marimo._messaging.cell_output import CellChannel
from marimo._messaging.console_output_worker import ConsoleMsg, buffered_writer
+from marimo._messaging.mimetypes import KnownMimeType
from marimo._messaging.types import (
KernelMessage,
Stderr,
@@ -178,7 +179,7 @@ class ThreadSafeStdout(Stdout):
# TODO(akshayka): maybe force the buffered writer to write
return
- def write(self, data: str) -> int:
+ def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:
assert self._stream.cell_id is not None
if 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 write
return
- def write(self, data: str) -> int:
+ def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:
assert self._stream.cell_id is not None
if 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.py
index f7465c5cc4..76c670ec05 100644
--- a/marimo/_messaging/tracebacks.py
+++ b/marimo/_messaging/tracebacks.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import sys
-from marimo._runtime.context.types import ContextNotInitializedError
+from marimo._messaging.types import Stderr
def _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 value
diff --git a/marimo/_messaging/types.py b/marimo/_messaging/types.py
index 7955edff9d..2758d32a5f 100644
--- a/marimo/_messaging/types.py
+++ b/marimo/_messaging/types.py
@@ -4,6 +4,7 @@ import io
from typing import Any, Dict, Optional, Tuple
from 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.py
index 4265ec356e..6327362629 100644
--- a/marimo/_pyodide/streams.py
+++ b/marimo/_pyodide/streams.py
@@ -8,6 +8,7 @@ from typing import Any, Callable, Iterable, Optional
from marimo import _loggers
from marimo._ast.cell import CellId_t
from marimo._messaging.cell_output import CellChannel, CellOutput
+from marimo._messaging.mimetypes import KnownMimeType
from marimo._messaging.ops import CellOp
from marimo._messaging.streams import STD_STREAM_MAX_BYTES
from 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 None
if 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 None
if 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.py
index 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 sys
from marimo._ast.cell import CellId_t
from marimo._messaging.cell_output import CellChannel
from marimo._messaging.ops import CellOp
+from marimo._messaging.tracebacks import write_traceback
from marimo._output import formatting
from marimo._output.rich_help import mddoc
from marimo._plugins.stateless.flex import vstack
@@ -13,7 +13,7 @@ from marimo._runtime.context import get_context
def 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.py
new file mode 100644
index 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.py
index 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.py
index 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.py
index 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.py
index 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.py
index a75e5804fe..354d684d51 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -13,6 +13,7 @@ import pytest
from marimo._ast.app import CellManager
from marimo._ast.cell import CellId_t
from marimo._config.config import DEFAULT_CONFIG
+from marimo._messaging.mimetypes import KnownMimeType
from 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 mimetype
self.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 mimetype
self.messages.append(data)
return len(data)