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 markdown text (#6848)

Myles Scolnick7be71d05e5bf
diff --git a/frontend/src/components/editor/Output.tsx b/frontend/src/components/editor/Output.tsx
index a39bdadb2a..a0bed03903 100644
--- a/frontend/src/components/editor/Output.tsx
+++ b/frontend/src/components/editor/Output.tsx
@@ -27,7 +27,6 @@ import {
} from "lucide-react";
import { useExpandedOutput } from "@/core/cells/outputs";
import { renderHTML } from "@/plugins/core/RenderHTML";
-import { LazyAnyLanguageCodeMirror } from "@/plugins/impl/code/LazyAnyLanguageCodeMirror";
import { Banner } from "@/plugins/impl/common/error-banner";
import type { TopLevelFacetedUnitSpec } from "@/plugins/impl/data-explorer/queries/types";
import { useTheme } from "@/theme/useTheme";
@@ -93,7 +92,14 @@ export const OutputRenderer: React.FC<{
typeof data === "string",
`Expected string data for mime=${mimetype}. Got ${typeof data}`,
);
- return <HtmlOutput className={channel} html={data} />;
+ // We don't sanitize HTML in text/html to allow for iframes or rich javascript content.
+ return (
+ <HtmlOutput
+ className={channel}
+ html={data}
+ alwaysSanitizeHtml={false}
+ />
+ );
case "text/plain":
invariant(
@@ -124,7 +130,7 @@ export const OutputRenderer: React.FC<{
typeof data === "string",
`Expected string data for mime=${mimetype}. Got ${typeof data}`,
);
- return renderHTML({ html: data });
+ return renderHTML({ html: data, alwaysSanitizeHtml: true });
case "video/mp4":
case "video/mpeg":
@@ -164,13 +170,7 @@ export const OutputRenderer: React.FC<{
`Expected string data for mime=${mimetype}. Got ${typeof data}`,
);
return (
- <LazyAnyLanguageCodeMirror
- theme={theme === "dark" ? "dark" : "light"}
- value={data}
- readOnly={true}
- editable={false}
- language="markdown"
- />
+ <HtmlOutput className={channel} html={data} alwaysSanitizeHtml={true} />
);
case "application/vnd.vegalite.v5+json":
case "application/vnd.vega.v5+json":
diff --git a/frontend/src/components/editor/output/CalloutOutput.tsx b/frontend/src/components/editor/output/CalloutOutput.tsx
index 886102757c..326b0b2aff 100644
--- a/frontend/src/components/editor/output/CalloutOutput.tsx
+++ b/frontend/src/components/editor/output/CalloutOutput.tsx
@@ -12,7 +12,7 @@ interface Props {
export const CalloutOutput: React.FC<Props> = memo(({ html, kind }) => {
return (
<div className={calloutStyles({ kind })}>
- <HtmlOutput html={html} />
+ <HtmlOutput html={html} alwaysSanitizeHtml={true} />
</div>
);
});
diff --git a/frontend/src/components/editor/output/HtmlOutput.tsx b/frontend/src/components/editor/output/HtmlOutput.tsx
index 8ed5811dca..16883434de 100644
--- a/frontend/src/components/editor/output/HtmlOutput.tsx
+++ b/frontend/src/components/editor/output/HtmlOutput.tsx
@@ -5,19 +5,20 @@ import { cn } from "../../../utils/cn";
interface Props {
html: string;
+ alwaysSanitizeHtml: boolean;
inline?: boolean;
className?: string;
}
export const HtmlOutput: React.FC<Props> = memo(
- ({ html, inline = false, className }) => {
+ ({ html, inline = false, className, alwaysSanitizeHtml }) => {
if (!html) {
return null;
}
return (
<div className={cn(className, { "inline-flex": inline, block: !inline })}>
- {renderHTML({ html })}
+ {renderHTML({ html, alwaysSanitizeHtml })}
</div>
);
},
diff --git a/frontend/src/components/editor/output/JsonOutput.tsx b/frontend/src/components/editor/output/JsonOutput.tsx
index 7eb5d62418..35a440a03c 100644
--- a/frontend/src/components/editor/output/JsonOutput.tsx
+++ b/frontend/src/components/editor/output/JsonOutput.tsx
@@ -192,7 +192,12 @@ const CollapsibleTextOutput = (props: { text: string }) => {
const LEAF_RENDERERS = {
"image/": (value: string) => <ImageOutput src={value} />,
"video/": (value: string) => <VideoOutput src={value} />,
- "text/html:": (value: string) => <HtmlOutput html={value} inline={true} />,
+ "text/html:": (value: string) => (
+ <HtmlOutput html={value} inline={true} alwaysSanitizeHtml={false} />
+ ),
+ "text/markdown:": (value: string) => (
+ <HtmlOutput html={value} inline={true} alwaysSanitizeHtml={true} />
+ ),
"text/plain+float:": (value: string) => <span>{value}</span>,
"text/plain+bigint:": (value: string) => <span>{value}</span>,
"text/plain+set:": (value: string) => <span>set{value}</span>,
diff --git a/frontend/src/components/editor/output/__tests__/HtmlOutput.test.tsx b/frontend/src/components/editor/output/__tests__/HtmlOutput.test.tsx
new file mode 100644
index 0000000000..141dfd68f2
--- /dev/null
+++ b/frontend/src/components/editor/output/__tests__/HtmlOutput.test.tsx
@@ -0,0 +1,134 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { render } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { HtmlOutput } from "../HtmlOutput";
+
+// Mock only the useSanitizeHtml hook, use real sanitizeHtml
+vi.mock("@/plugins/core/sanitize", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("@/plugins/core/sanitize")>();
+ return {
+ ...actual,
+ useSanitizeHtml: vi.fn(() => false),
+ };
+});
+
+describe("HtmlOutput", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ test("renders HTML content", () => {
+ const result = render(
+ <HtmlOutput html="<p>Hello World</p>" alwaysSanitizeHtml={false} />,
+ );
+ expect(result.container.firstChild).toMatchInlineSnapshot(`
+ <div
+ class="block"
+ >
+ <p>
+ Hello World
+ </p>
+ </div>
+ `);
+ });
+
+ test("renders inline when inline prop is true", () => {
+ const result = render(
+ <HtmlOutput
+ html="<span>Inline</span>"
+ inline={true}
+ alwaysSanitizeHtml={false}
+ />,
+ );
+ expect(result.container.firstChild).toMatchInlineSnapshot(`
+ <div
+ class="inline-flex"
+ >
+ <span>
+ Inline
+ </span>
+ </div>
+ `);
+ });
+
+ test("renders block by default", () => {
+ const result = render(
+ <HtmlOutput html="<p>Block</p>" alwaysSanitizeHtml={false} />,
+ );
+ expect(result.container.firstChild).toMatchInlineSnapshot(`
+ <div
+ class="block"
+ >
+ <p>
+ Block
+ </p>
+ </div>
+ `);
+ });
+
+ test("applies custom className", () => {
+ const result = render(
+ <HtmlOutput
+ html="<p>Test</p>"
+ className="custom-class"
+ alwaysSanitizeHtml={false}
+ />,
+ );
+ expect(result.container.firstChild).toMatchInlineSnapshot(`
+ <div
+ class="custom-class block"
+ >
+ <p>
+ Test
+ </p>
+ </div>
+ `);
+ });
+
+ test("handles empty html", () => {
+ const { container } = render(
+ <HtmlOutput html="" alwaysSanitizeHtml={false} />,
+ );
+ expect(container.textContent).toBe("");
+ });
+
+ test("alwaysSanitizeHtml=true sanitizes content", () => {
+ const result = render(
+ <HtmlOutput
+ html="<p>Content</p><script>alert('test')</script>"
+ alwaysSanitizeHtml={true}
+ />,
+ );
+ expect(result.container.firstChild).toMatchInlineSnapshot(`
+ <div
+ class="block"
+ >
+ <p>
+ Content
+ </p>
+ </div>
+ `);
+ });
+
+ test("alwaysSanitizeHtml=false allows scripts when useSanitizeHtml=false", () => {
+ const result = render(
+ <HtmlOutput
+ html="<p>Content</p><script>alert('test')</script>"
+ alwaysSanitizeHtml={false}
+ />,
+ );
+ expect(result.container.firstChild).toMatchInlineSnapshot(`
+ <div
+ class="block"
+ >
+ <p>
+ Content
+ </p>
+ <script>
+ alert('test')
+ </script>
+ </div>
+ `);
+ });
+});
diff --git a/frontend/src/plugins/core/RenderHTML.tsx b/frontend/src/plugins/core/RenderHTML.tsx
index 144c9a2d52..33b1b1408f 100644
--- a/frontend/src/plugins/core/RenderHTML.tsx
+++ b/frontend/src/plugins/core/RenderHTML.tsx
@@ -20,6 +20,11 @@ type TransformFn = NonNullable<HTMLReactParserOptions["transform"]>;
interface Options {
html: string;
+ /**
+ * Whether to sanitize the HTML.
+ * @default true
+ */
+ alwaysSanitizeHtml?: boolean;
additionalReplacements?: ReplacementFn[];
}
@@ -139,31 +144,51 @@ const CopyableCode = ({ children }: { children: ReactNode }) => {
);
};
-export const renderHTML = ({ html, additionalReplacements = [] }: Options) => {
+/**
+ *
+ * @param html - The HTML to render.
+ * @param additionalReplacements - Additional replacements to apply to the HTML.
+ * @param alwaysSanitizeHtml - Whether to sanitize the HTML.
+ * @returns
+ */
+export const renderHTML = ({
+ html,
+ additionalReplacements = [],
+ alwaysSanitizeHtml = true,
+}: Options) => {
return (
- <RenderHTMLComponent
+ <RenderHTML
html={html}
+ alwaysSanitizeHtml={alwaysSanitizeHtml}
additionalReplacements={additionalReplacements}
/>
);
};
-const RenderHTMLComponent = ({
+const RenderHTML = ({
html,
additionalReplacements = [],
+ alwaysSanitizeHtml,
}: Options) => {
const shouldSanitizeHtml = useSanitizeHtml();
+
const sanitizedHtml = useMemo(() => {
- if (shouldSanitizeHtml) {
+ if (alwaysSanitizeHtml || shouldSanitizeHtml) {
return sanitizeHtml(html);
}
return html;
- }, [html, shouldSanitizeHtml]);
+ }, [html, alwaysSanitizeHtml, shouldSanitizeHtml]);
- return parseHtml({ html: sanitizedHtml, additionalReplacements });
+ return parseHtml({
+ html: sanitizedHtml,
+ additionalReplacements,
+ });
};
-function parseHtml({ html, additionalReplacements = [] }: Options) {
+function parseHtml({
+ html,
+ additionalReplacements = [],
+}: Pick<Options, "html" | "additionalReplacements">) {
const renderFunctions: ReplacementFn[] = [
replaceValidTags,
replaceValidIframes,
diff --git a/frontend/src/plugins/core/__test__/renderHTML-sanitization.test.tsx b/frontend/src/plugins/core/__test__/renderHTML-sanitization.test.tsx
new file mode 100644
index 0000000000..c928e672c6
--- /dev/null
+++ b/frontend/src/plugins/core/__test__/renderHTML-sanitization.test.tsx
@@ -0,0 +1,131 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { render } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { renderHTML } from "../RenderHTML";
+
+// Mock only the useSanitizeHtml hook, use real sanitizeHtml
+vi.mock("../sanitize", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../sanitize")>();
+ return {
+ ...actual,
+ useSanitizeHtml: vi.fn(() => false), // Default to not sanitizing based on state
+ };
+});
+
+describe("renderHTML with alwaysSanitizeHtml", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ test("alwaysSanitizeHtml=true forces sanitization even when useSanitizeHtml=false", () => {
+ const html = "<p>Test</p><script>alert('xss')</script>";
+ const result = renderHTML({ html, alwaysSanitizeHtml: true });
+ const { container } = render(result);
+ expect(container.innerHTML).toMatchInlineSnapshot(`"<p>Test</p>"`);
+ });
+
+ test("alwaysSanitizeHtml=false respects useSanitizeHtml=false (no sanitization)", () => {
+ const html = "<p>Test</p><script>alert('test')</script>";
+ const result = renderHTML({ html, alwaysSanitizeHtml: false });
+ const { container } = render(result);
+ expect(container.innerHTML).toMatchInlineSnapshot(
+ `"<p>Test</p><script>alert('test')</script>"`,
+ );
+ });
+
+ test("alwaysSanitizeHtml=false respects useSanitizeHtml=true (sanitize)", async () => {
+ // Import to get access to the mock
+ const sanitizeModule = await import("../sanitize");
+ vi.mocked(sanitizeModule.useSanitizeHtml).mockReturnValue(true);
+
+ const html = "<p>Test</p><script>alert('test')</script>";
+ const result = renderHTML({ html, alwaysSanitizeHtml: false });
+ const { container } = render(result);
+ expect(container.innerHTML).toMatchInlineSnapshot(`"<p>Test</p>"`);
+ });
+
+ test("default alwaysSanitizeHtml=true sanitizes by default", () => {
+ const html = "<p>Test</p><script>alert('xss')</script>";
+ // Don't pass alwaysSanitizeHtml (should default to true)
+ const result = renderHTML({ html });
+
+ const { container } = render(result);
+
+ // Script should be removed by default sanitization
+ expect(container.innerHTML).toMatchInlineSnapshot(`"<p>Test</p>"`);
+ });
+
+ test("renders sanitized content correctly", () => {
+ const html = "<p>Safe content</p><script>alert('unsafe')</script>";
+ const result = renderHTML({ html, alwaysSanitizeHtml: true });
+ const { container } = render(result);
+ expect(container.innerHTML).toMatchInlineSnapshot(`"<p>Safe content</p>"`);
+ });
+
+ test("renders unsanitized content when allowed", () => {
+ const html =
+ '<p>Safe content</p><form action="//evil.com"><input type="text"></form>';
+ const result = renderHTML({ html, alwaysSanitizeHtml: false });
+ const { container } = render(result);
+ expect(container.innerHTML).toMatchInlineSnapshot(
+ `"<p>Safe content</p><form action="//evil.com"><input type="text"></form>"`,
+ );
+ });
+
+ test("sanitization happens before parsing", () => {
+ const html = '<p>Content</p><div onload="alert(1)">Div</div>';
+ const result = renderHTML({ html, alwaysSanitizeHtml: true });
+ const { container } = render(result);
+ expect(container.innerHTML).toMatchInlineSnapshot(
+ `"<p>Content</p><div>Div</div>"`,
+ );
+ });
+});
+
+describe("renderHTML sanitization integration", () => {
+ test("text/markdown content should be sanitized", () => {
+ const markdownHtml =
+ '<span class="markdown"><p>Content</p><script>alert("xss")</script></span>';
+ const result = renderHTML({ html: markdownHtml, alwaysSanitizeHtml: true });
+ const { container } = render(result);
+ expect(container.innerHTML).toMatchInlineSnapshot(
+ `"<span class="markdown"><p>Content</p></span>"`,
+ );
+ });
+
+ test("data attributes preserved with sanitization", () => {
+ const richHtml = '<div data-custom="test"><p>Content</p></div>';
+ const result = renderHTML({
+ html: richHtml,
+ alwaysSanitizeHtml: true,
+ });
+ const { container } = render(result);
+ expect(container.innerHTML).toMatchInlineSnapshot(
+ `"<div data-custom="test"><p>Content</p></div>"`,
+ );
+ });
+
+ test("data attributes preserved without sanitization", () => {
+ const richHtml = '<div data-custom="test"><p>Content</p></div>';
+ const result = renderHTML({
+ html: richHtml,
+ alwaysSanitizeHtml: false,
+ });
+ const { container } = render(result);
+ expect(container.innerHTML).toMatchInlineSnapshot(
+ `"<div data-custom="test"><p>Content</p></div>"`,
+ );
+ });
+
+ test("dangerous content is sanitized when alwaysSanitizeHtml=true", () => {
+ const dangerousHtml = '<img src=x onerror="alert(1)"><p>Content</p>';
+ const result = renderHTML({
+ html: dangerousHtml,
+ alwaysSanitizeHtml: true,
+ });
+ const { container } = render(result);
+ expect(container.innerHTML).toMatchInlineSnapshot(
+ `"<img src="x"><p>Content</p>"`,
+ );
+ });
+});
diff --git a/frontend/src/plugins/core/__test__/sanitize.test.ts b/frontend/src/plugins/core/__test__/sanitize.test.ts
new file mode 100644
index 0000000000..ab90e8a4b9
--- /dev/null
+++ b/frontend/src/plugins/core/__test__/sanitize.test.ts
@@ -0,0 +1,465 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, expect, test } from "vitest";
+import { sanitizeHtml } from "../sanitize";
+
+describe("sanitizeHtml", () => {
+ test("renders basic HTML", () => {
+ const html = "<h1>Hello World</h1>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`"<h1>Hello World</h1>"`);
+ });
+
+ test("renders nested HTML", () => {
+ const html = "<div><p>Paragraph</p><span>Span</span></div>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<div><p>Paragraph</p><span>Span</span></div>"`,
+ );
+ });
+
+ test("removes script tags", () => {
+ const html = "<div>Hello</div><script>alert('XSS')</script>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`"<div>Hello</div>"`);
+ });
+
+ test("removes inline script in onclick", () => {
+ const html = "<button onclick=\"alert('XSS')\">Click me</button>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<button>Click me</button>"`,
+ );
+ });
+
+ test("removes javascript: protocol in href", () => {
+ const html = "<a href=\"javascript:alert('XSS')\">Link</a>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<a target="_self">Link</a>"`,
+ );
+ });
+
+ test("removes onerror attribute", () => {
+ const html = '<img src="x" onerror="alert(\'XSS\')" />';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`"<img src="x">"`);
+ });
+
+ test("keeps form tags but removes action attribute", () => {
+ const html = '<form action="/submit"><input type="text"/></form>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<form action="/submit"><input type="text"></form>"`,
+ );
+ });
+
+ test("removes iframe tags", () => {
+ const html = '<iframe src="https://evil.com"></iframe>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`""`);
+ });
+
+ test("removes embed tags", () => {
+ const html = '<embed src="https://evil.com" />';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`""`);
+ });
+
+ test("removes object tags", () => {
+ const html = '<object data="https://evil.com"></object>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`""`);
+ });
+
+ test("preserves safe anchor with target=_blank", () => {
+ const html = '<a href="https://example.com" target="_blank">Link</a>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<a href="https://example.com" target="_blank" rel="noopener">Link</a>"`,
+ );
+ });
+
+ test("adds target=_self to anchor without target", () => {
+ const html = '<a href="https://example.com">Link</a>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<a href="https://example.com" target="_self">Link</a>"`,
+ );
+ });
+
+ test("preserves target=_self on anchor", () => {
+ const html = '<a href="https://example.com" target="_self">Link</a>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<a href="https://example.com" target="_self">Link</a>"`,
+ );
+ });
+
+ test("preserves target=_parent on anchor", () => {
+ const html = '<a href="https://example.com" target="_parent">Link</a>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<a href="https://example.com" target="_parent">Link</a>"`,
+ );
+ });
+
+ test("preserves SVG elements", () => {
+ const html =
+ '<svg width="100" height="100"><circle cx="50" cy="50" r="40" /></svg>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<svg width="100" height="100"><circle cx="50" cy="50" r="40"></circle></svg>"`,
+ );
+ });
+
+ test("removes script from SVG", () => {
+ const html = '<svg><script>alert("XSS")</script><circle r="10" /></svg>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<svg><circle r="10"></circle></svg>"`,
+ );
+ });
+
+ test("preserves MathML", () => {
+ const html = "<math><mi>x</mi><mo>=</mo><mn>2</mn></math>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<math><mi>x</mi><mo>=</mo><mn>2</mn></math>"`,
+ );
+ });
+
+ test("preserves custom marimo elements", () => {
+ const html = '<marimo-slider value="50"></marimo-slider>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<marimo-slider value="50"></marimo-slider>"`,
+ );
+ });
+
+ test("preserves marimo elements with valid naming", () => {
+ const html = "<marimo-custom-element></marimo-custom-element>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<marimo-custom-element></marimo-custom-element>"`,
+ );
+ });
+
+ test("removes invalid custom elements (not marimo-*)", () => {
+ const html = "<custom-element>Content</custom-element>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`"Content"`);
+ });
+
+ test("keeps style tags with FORCE_BODY", () => {
+ const html = "<style>body { color: red; }</style><p>Text</p>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<style>body { color: red; }</style><p>Text</p>"`,
+ );
+ });
+
+ test("removes link tags", () => {
+ const html = '<link rel="stylesheet" href="evil.css" /><p>Text</p>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`"<p>Text</p>"`);
+ });
+
+ test("removes meta tags", () => {
+ const html = '<meta http-equiv="refresh" content="0;url=evil.com" />';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`""`);
+ });
+
+ test("removes base tags", () => {
+ const html = '<base href="https://evil.com" /><p>Text</p>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`"<p>Text</p>"`);
+ });
+
+ test("preserves safe HTML entities", () => {
+ const html = "<p>&lt;div&gt; &amp; &quot;quotes&quot;</p>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<p>&lt;div&gt; &amp; "quotes"</p>"`,
+ );
+ });
+
+ test("preserves data attributes", () => {
+ const html = '<div data-id="123" data-name="test">Content</div>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<div data-id="123" data-name="test">Content</div>"`,
+ );
+ });
+
+ test("preserves aria attributes", () => {
+ const html = '<button aria-label="Close" aria-hidden="true">X</button>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<button aria-label="Close" aria-hidden="true">X</button>"`,
+ );
+ });
+
+ test("preserves class and id attributes", () => {
+ const html = '<div id="main" class="container primary">Content</div>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<div id="main" class="container primary">Content</div>"`,
+ );
+ });
+
+ test("removes dangerous event handlers", () => {
+ const html =
+ '<div onload="alert(1)" onmouseover="alert(2)" onfocus="alert(3)">Text</div>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`"<div>Text</div>"`);
+ });
+
+ test("handles empty string", () => {
+ const html = "";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`""`);
+ });
+
+ test("handles text without tags", () => {
+ const html = "Just plain text";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`"Just plain text"`);
+ });
+
+ test("handles malformed HTML", () => {
+ const html = "<div><p>Unclosed div";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<div><p>Unclosed div</p></div>"`,
+ );
+ });
+
+ test("removes data URIs with javascript", () => {
+ const html = '<a href="data:text/html,<script>alert(1)</script>">Link</a>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<a target="_self">Link</a>"`,
+ );
+ });
+
+ test("preserves safe data URIs", () => {
+ const html = '<img src="data:image/png;base64,iVBORw0KGgo=" />';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<img src="data:image/png;base64,iVBORw0KGgo=">"`,
+ );
+ });
+
+ test("removes srcdoc attribute from iframe", () => {
+ const html = '<iframe srcdoc="<script>alert(1)</script>"></iframe>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`""`);
+ });
+
+ test("handles complex nested structure", () => {
+ const html = `
+ <div class="container">
+ <header>
+ <h1>Title</h1>
+ <nav><a href="/home">Home</a></nav>
+ </header>
+ <main>
+ <article>
+ <p>Content</p>
+ </article>
+ </main>
+ </div>
+ `;
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`
+ "
+ <div class="container">
+ <header>
+ <h1>Title</h1>
+ <nav><a href="/home" target="_self">Home</a></nav>
+ </header>
+ <main>
+ <article>
+ <p>Content</p>
+ </article>
+ </main>
+ </div>
+ "
+ `);
+ });
+
+ test("keeps marquee and blink tags (not considered dangerous by DOMPurify)", () => {
+ const html = "<marquee>Scrolling text</marquee><blink>Blinking</blink>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<marquee>Scrolling text</marquee><blink>Blinking</blink>"`,
+ );
+ });
+
+ test("preserves table structures", () => {
+ const html = "<table><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<table><tbody><tr><td>Cell 1</td><td>Cell 2</td></tr></tbody></table>"`,
+ );
+ });
+
+ test("removes xml-stylesheet processing instructions", () => {
+ const html =
+ '<?xml-stylesheet href="evil.xsl" type="text/xsl"?><div>Text</div>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`"<div>Text</div>"`);
+ });
+
+ test("removes use element from SVG", () => {
+ const html = '<svg><use xlink:href="#icon"></use></svg>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`"<svg></svg>"`);
+ });
+
+ test("removes javascript in SVG href", () => {
+ const html =
+ '<svg><a href="javascript:alert(1)"><text>Click</text></a></svg>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<svg><a><text>Click</text></a></svg>"`,
+ );
+ });
+
+ test("preserves img with valid src", () => {
+ const html = '<img src="https://example.com/image.png" alt="Image" />';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<img src="https://example.com/image.png" alt="Image">"`,
+ );
+ });
+
+ test("handles multiple scripts interleaved", () => {
+ const html =
+ "<div>Text1</div><script>evil1()</script><p>Text2</p><script>evil2()</script>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<div>Text1</div><p>Text2</p>"`,
+ );
+ });
+
+ test("removes frameset and frame tags", () => {
+ const html = '<frameset><frame src="page.html" /></frameset>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`""`);
+ });
+
+ test("handles vbscript: protocol", () => {
+ const html = '<a href="vbscript:msgbox()">Link</a>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<a target="_self">Link</a>"`,
+ );
+ });
+
+ test("removes autofocus and onfocus from input", () => {
+ const html = '<input type="hidden" autofocus onfocus="alert(1)" />';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`"<input type="hidden">"`);
+ });
+
+ test("removes formaction attribute", () => {
+ const html = '<button formaction="javascript:alert(1)">Click</button>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<button>Click</button>"`,
+ );
+ });
+
+ test("handles nested script-like content", () => {
+ const html = "<div>&lt;script&gt;alert(1)&lt;/script&gt;</div>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<div>&lt;script&gt;alert(1)&lt;/script&gt;</div>"`,
+ );
+ });
+
+ test("preserves valid inline styles", () => {
+ const html = '<div style="color: blue; font-size: 14px;">Styled</div>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<div style="color: blue; font-size: 14px;">Styled</div>"`,
+ );
+ });
+
+ test("keeps expression() in styles (legacy IE only)", () => {
+ const html = '<div style="width: expression(alert(1));">Text</div>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<div style="width: expression(alert(1));">Text</div>"`,
+ );
+ });
+
+ test("keeps moz-binding in styles (legacy Firefox only)", () => {
+ const html = '<div style="-moz-binding: url(xss.xml#xss)">Text</div>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<div style="-moz-binding: url(xss.xml#xss)">Text</div>"`,
+ );
+ });
+
+ test("preserves title and alt attributes", () => {
+ const html = '<img src="pic.jpg" alt="Picture" title="A nice picture" />';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<img src="pic.jpg" alt="Picture" title="A nice picture">"`,
+ );
+ });
+
+ test("handles multiple targets on links", () => {
+ const html = '<a href="/" target="_top">Link</a>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<a href="/" target="_top">Link</a>"`,
+ );
+ });
+
+ test("removes on* attributes comprehensively", () => {
+ const html =
+ '<div onabort="alert(1)" onblur="alert(2)" onchange="alert(3)" ondblclick="alert(4)">Text</div>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`"<div>Text</div>"`);
+ });
+
+ test("removes SVG foreignObject", () => {
+ const html =
+ "<svg><foreignObject><body><p>Text</p></body></foreignObject></svg>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`"<svg></svg>"`);
+ });
+
+ test("removes xlink:href with javascript in SVG", () => {
+ const html = '<svg><a xlink:href="javascript:alert(1)">Click</a></svg>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<svg><a>Click</a></svg>"`,
+ );
+ });
+
+ test("preserves role attributes", () => {
+ const html = '<div role="button" tabindex="0">Clickable</div>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<div role="button" tabindex="0">Clickable</div>"`,
+ );
+ });
+
+ test("handles HTML comments", () => {
+ const html = "<!-- Comment --><p>Text</p>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`"<p>Text</p>"`);
+ });
+
+ test("removes conditional comments", () => {
+ const html = "<!--[if IE]><script>alert(1)</script><![endif]--><p>Text</p>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(`"<p>Text</p>"`);
+ });
+
+ test("preserves pre and code elements", () => {
+ const html = "<pre><code>const x = 1;</code></pre>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<pre><code>const x = 1;</code></pre>"`,
+ );
+ });
+
+ test("handles mixed content with scripts", () => {
+ const html =
+ "<div><p>Safe</p><script>evil()</script><p>More safe</p></div>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<div><p>Safe</p><p>More safe</p></div>"`,
+ );
+ });
+
+ test("preserves video and audio elements", () => {
+ const html = '<video src="video.mp4" controls></video>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<video src="video.mp4" controls=""></video>"`,
+ );
+ });
+
+ test("handles source elements in video", () => {
+ const html =
+ '<video controls><source src="video.mp4" type="video/mp4" /></video>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<video controls=""><source src="video.mp4" type="video/mp4"></video>"`,
+ );
+ });
+
+ test("removes import statement in style", () => {
+ const html = '<style>@import url("evil.css");</style>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<style>@import url("evil.css");</style>"`,
+ );
+ });
+
+ test("handles HTML5 semantic elements", () => {
+ const html =
+ "<article><section><header>Title</header><footer>Footer</footer></section></article>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<article><section><header>Title</header><footer>Footer</footer></section></article>"`,
+ );
+ });
+
+ test("preserves canvas element", () => {
+ const html = '<canvas id="myCanvas" width="200" height="100"></canvas>';
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<canvas id="myCanvas" width="200" height="100"></canvas>"`,
+ );
+ });
+
+ test("handles details and summary elements", () => {
+ const html =
+ "<details><summary>Click me</summary><p>Hidden content</p></details>";
+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(
+ `"<details><summary>Click me</summary><p>Hidden content</p></details>"`,
+ );
+ });
+});
diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsx
index 4fc3874758..84af62af57 100644
--- a/frontend/src/plugins/core/registerReactComponent.tsx
+++ b/frontend/src/plugins/core/registerReactComponent.tsx
@@ -362,7 +362,8 @@ export function registerReactComponent<T>(plugin: IPlugin<T, unknown>): void {
* Get the children of the element as React nodes.
*/
private getChildren(): React.ReactNode {
- return renderHTML({ html: this.innerHTML });
+ // We don't sanitize the HTML here because it could be an iframe inside of tabs or accordions
+ return renderHTML({ html: this.innerHTML, alwaysSanitizeHtml: false });
}
/**
diff --git a/frontend/src/plugins/core/sanitize.ts b/frontend/src/plugins/core/sanitize.ts
index e18baaa051..4a589ab073 100644
--- a/frontend/src/plugins/core/sanitize.ts
+++ b/frontend/src/plugins/core/sanitize.ts
@@ -26,6 +26,9 @@ const sanitizeHtmlAtom = atom<boolean>((get) => {
return true;
});
+/**
+ * Whether to sanitize the html.
+ */
export function useSanitizeHtml() {
return useAtomValue(sanitizeHtmlAtom);
}
diff --git a/marimo/_output/formatters/df_formatters.py b/marimo/_output/formatters/df_formatters.py
index 6b565a86a7..f95a81ce4f 100644
--- a/marimo/_output/formatters/df_formatters.py
+++ b/marimo/_output/formatters/df_formatters.py
@@ -1,7 +1,6 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-import os
import re
from enum import Enum
from typing import Any
@@ -14,6 +13,7 @@ from marimo._output.formatters.formatter_factory import (
FormatterFactory,
Unregister,
)
+from marimo._output.hypertext import is_no_js
from marimo._plugins.stateless.json_output import json_output
from marimo._plugins.stateless.mermaid import mermaid
from marimo._plugins.stateless.plain_text import plain_text
@@ -30,7 +30,7 @@ def include_opinionated() -> bool:
runtime_context_installed,
)
- if os.getenv("MARIMO_NO_JS", "false").lower() == "true":
+ if is_no_js():
return False
if runtime_context_installed():
diff --git a/marimo/_output/formatting.py b/marimo/_output/formatting.py
index 447bd915ca..a2cc53f9e3 100644
--- a/marimo/_output/formatting.py
+++ b/marimo/_output/formatting.py
@@ -18,7 +18,6 @@ taking precedence over the MIME protocol.
from __future__ import annotations
import json
-import os
import traceback
from dataclasses import dataclass
from html import escape
@@ -29,7 +28,7 @@ from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.builder import h
from marimo._output.formatters.repr_formatters import maybe_get_repr_formatter
from marimo._output.formatters.utils import src_or_src_doc
-from marimo._output.hypertext import Html
+from marimo._output.hypertext import Html, is_no_js
from marimo._output.rich_help import mddoc
from marimo._output.utils import flatten_string
from marimo._plugins.core.media import io_to_data_url
@@ -158,9 +157,7 @@ def get_formatter(
# If not explicitly opinionated, we defer to the environment.
if include_opinionated is None:
- include_opinionated = (
- os.getenv("MARIMO_NO_JS", "false").lower() == "false"
- )
+ include_opinionated = not is_no_js()
# Plain opts out of opinionated formatters
if isinstance(obj, Plain):
diff --git a/marimo/_output/hypertext.py b/marimo/_output/hypertext.py
index abf162751a..80b16e5766 100644
--- a/marimo/_output/hypertext.py
+++ b/marimo/_output/hypertext.py
@@ -5,7 +5,7 @@ import os
import weakref
from contextlib import contextmanager
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Any, Literal, Optional, cast, final
+from typing import TYPE_CHECKING, Any, Literal, Optional, cast
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.mime import MIME
@@ -136,9 +136,8 @@ class Html(MIME):
"""A string of HTML representing this element."""
return self._text
- @final
def _mime_(self) -> tuple[KnownMimeType, str]:
- no_js = os.getenv("MARIMO_NO_JS", "false").lower() == "true"
+ no_js = is_no_js()
if no_js and hasattr(self, "_repr_png_"):
return (
"image/png",
@@ -289,9 +288,7 @@ class Html(MIME):
return self.text
-def _js(text: str) -> Html:
- # TODO: interpolation of Python values to javascript
- return Html("<script>" + text + "</script>")
+MARIMO_NO_JS_KEY = "MARIMO_NO_JS"
@contextmanager
@@ -304,9 +301,18 @@ def patch_html_for_non_interactive_output() -> Iterator[None]:
# thread
# This won't work when we are running a marimo server and are auto-exporting
# with this enabled.
- old_no_js = os.getenv("MARIMO_NO_JS", "false")
+ old_no_js = os.getenv(MARIMO_NO_JS_KEY, "false")
try:
- os.environ["MARIMO_NO_JS"] = "true"
+ os.environ[MARIMO_NO_JS_KEY] = "true"
yield
finally:
- os.environ["MARIMO_NO_JS"] = old_no_js
+ os.environ[MARIMO_NO_JS_KEY] = old_no_js
+
+
+def is_no_js() -> bool:
+ """Whether to render HTML objects as best as possible assuming
+ that this will be rendered without javascript.
+
+ For example, prefer images or markdown over rich HTML output.
+ """
+ return os.getenv(MARIMO_NO_JS_KEY, "false").lower() == "true"
diff --git a/marimo/_output/md.py b/marimo/_output/md.py
index c8f9d3dc81..fd808f78f0 100644
--- a/marimo/_output/md.py
+++ b/marimo/_output/md.py
@@ -13,7 +13,8 @@ import markdown # type: ignore
import markdown.preprocessors # type: ignore
import pymdownx.emoji # type: ignore
-from marimo._output.hypertext import Html
+from marimo._messaging.mimetypes import KnownMimeType
+from marimo._output.hypertext import Html, is_no_js
from marimo._output.md_extensions.breakless_lists import (
BreaklessListsExtension,
)
@@ -258,6 +259,14 @@ class _md(Html):
def _repr_markdown_(self) -> str:
return self._markdown_text
+ def _mime_(self) -> tuple[KnownMimeType, str]:
+ no_js = is_no_js()
+ if no_js:
+ return ("text/markdown", self._markdown_text)
+ # We return text/markdown instead of text/html
+ # so the frontend sanitizes the HTML
+ return ("text/markdown", self.text)
+
def __format__(self, spec: str) -> str:
"""
This overrides the default HTML formatting behavior to return the original
diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.py
index 29dca0a8cf..dc787b4bb1 100644
--- a/marimo/_server/file_manager.py
+++ b/marimo/_server/file_manager.py
@@ -91,13 +91,6 @@ class AppFileManager:
detail=f"File {filename} already exists",
)
- def _assert_path_is_the_same(self, filename: str) -> None:
- if self.filename is not None and not self._is_same_path(filename):
- raise HTTPException(
- status_code=HTTPStatus.BAD_REQUEST,
- detail="Save handler cannot rename files.",
- )
-
def _create_parent_directories(self, filename: str) -> None:
try:
pathlib.Path(filename).parent.mkdir(parents=True, exist_ok=True)
diff --git a/tests/_islands/snapshots/island-mimetypes.txt b/tests/_islands/snapshots/island-mimetypes.txt
index 602e77dfb7..507f4b8f0b 100644
--- a/tests/_islands/snapshots/island-mimetypes.txt
+++ b/tests/_islands/snapshots/island-mimetypes.txt
@@ -4,7 +4,7 @@
data-reactive="true"
>
<marimo-cell-output>
- <span class="markdown prose dark:prose-invert contents"><span class="paragraph">Hello, islands!</span></span>
+ <marimo-mime-renderer data-mime='&quot;text/markdown&quot;' data-data='&quot;&lt;span class=&#92;&quot;markdown prose dark:prose-invert contents&#92;&quot;&gt;&lt;span class=&#92;&quot;paragraph&#92;&quot;&gt;Hello, islands!&lt;/span&gt;&lt;/span&gt;&quot;'></marimo-mime-renderer>
</marimo-cell-output>
<marimo-cell-code hidden>mo.md('Hello%2C%20islands!')</marimo-cell-code>
</marimo-island>
@@ -34,7 +34,7 @@
data-reactive="true"
>
<marimo-cell-output>
- <marimo-json-output data-json-data='[1,&quot;text/html:&lt;span class=&#92;&quot;markdown prose dark:prose-invert contents&#92;&quot;&gt;&lt;span class=&#92;&quot;paragraph&#92;&quot;&gt;Hello&lt;/span&gt;&lt;/span&gt;&quot;]' data-value-types='&quot;python&quot;'></marimo-json-output>
+ <marimo-json-output data-json-data='[1,&quot;text/markdown:&lt;span class=&#92;&quot;markdown prose dark:prose-invert contents&#92;&quot;&gt;&lt;span class=&#92;&quot;paragraph&#92;&quot;&gt;Hello&lt;/span&gt;&lt;/span&gt;&quot;]' data-value-types='&quot;python&quot;'></marimo-json-output>
</marimo-cell-output>
<marimo-cell-code hidden>%5B1%2C%20mo.md('Hello')%5D</marimo-cell-code>
</marimo-island>
\ No newline at end of file
diff --git a/tests/_islands/snapshots/island-no-code.txt b/tests/_islands/snapshots/island-no-code.txt
index 3410c740be..8707d5dc0e 100644
--- a/tests/_islands/snapshots/island-no-code.txt
+++ b/tests/_islands/snapshots/island-no-code.txt
@@ -4,7 +4,7 @@
data-reactive="true"
>
<marimo-cell-output>
- <span class="markdown prose dark:prose-invert contents"><span class="paragraph">Hello, islands!</span></span>
+ <marimo-mime-renderer data-mime='&quot;text/markdown&quot;' data-data='&quot;&lt;span class=&#92;&quot;markdown prose dark:prose-invert contents&#92;&quot;&gt;&lt;span class=&#92;&quot;paragraph&#92;&quot;&gt;Hello, islands!&lt;/span&gt;&lt;/span&gt;&quot;'></marimo-mime-renderer>
</marimo-cell-output>
<marimo-cell-code hidden>mo.md('Hello%2C%20islands!')</marimo-cell-code>
</marimo-island>
\ No newline at end of file
diff --git a/tests/_islands/snapshots/island.txt b/tests/_islands/snapshots/island.txt
index 3410c740be..8707d5dc0e 100644
--- a/tests/_islands/snapshots/island.txt
+++ b/tests/_islands/snapshots/island.txt
@@ -4,7 +4,7 @@
data-reactive="true"
>
<marimo-cell-output>
- <span class="markdown prose dark:prose-invert contents"><span class="paragraph">Hello, islands!</span></span>
+ <marimo-mime-renderer data-mime='&quot;text/markdown&quot;' data-data='&quot;&lt;span class=&#92;&quot;markdown prose dark:prose-invert contents&#92;&quot;&gt;&lt;span class=&#92;&quot;paragraph&#92;&quot;&gt;Hello, islands!&lt;/span&gt;&lt;/span&gt;&quot;'></marimo-mime-renderer>
</marimo-cell-output>
<marimo-cell-code hidden>mo.md('Hello%2C%20islands!')</marimo-cell-code>
</marimo-island>
\ No newline at end of file
diff --git a/tests/_islands/snapshots/markdown.txt b/tests/_islands/snapshots/markdown.txt
index 467d116a3c..7855486385 100644
--- a/tests/_islands/snapshots/markdown.txt
+++ b/tests/_islands/snapshots/markdown.txt
@@ -1,18 +1,10 @@
<marimo-island
- data-app-id="main"
- data-cell-id="Hbol"
- data-reactive="true"
- >
- <marimo-cell-output>
- <span class="markdown prose dark:prose-invert contents"><h1 id="hello-markdown">Hello, Markdown!</h1>
-<span class="paragraph">This is a paragsraph.</span>
-<div class="language-python3 codehilite"><pre><span></span><code><span class="n">mo</span><span class="o">.</span><span class="n">md</span><span class="p">(</span>
-<span class="w"> </span><span class="sd">&#39;&#39;&#39;</span>
-<span class="sd"> # Hello, Markdown!</span>
-<span class="sd"> This is a paragraph.</span>
-<span class="sd"> &#39;&#39;&#39;</span>
-<span class="p">)</span>
-</code></pre></div></span>
- </marimo-cell-output>
- <marimo-cell-code hidden>%0Aimport%20marimo%20as%20mo%0Amo.md(%0A%20%20%20%20%22%22%22%0A%20%20%20%20%23%20Hello%2C%20Markdown!%0A%0A%20%20%20%20This%20is%20a%20paragsraph.%0A%0A%20%20%20%20%60%60%60python3%0A%20%20%20%20mo.md(%0A%20%20%20%20%20%20%20%20'''%0A%20%20%20%20%20%20%20%20%23%20Hello%2C%20Markdown!%0A%0A%20%20%20%20%20%20%20%20This%20is%20a%20paragraph.%0A%20%20%20%20%20%20%20%20'''%0A%20%20%20%20)%0A%20%20%20%20%60%60%60%0A%20%20%20%20%22%22%22%0A)%0A</marimo-cell-code>
- </marimo-island>
\ No newline at end of file
+ data-app-id="main"
+ data-cell-id="Hbol"
+ data-reactive="true"
+>
+ <marimo-cell-output>
+ <marimo-mime-renderer data-mime='&quot;text/markdown&quot;' data-data='&quot;&lt;span class=&#92;&quot;markdown prose dark:prose-invert contents&#92;&quot;&gt;&lt;h1 id=&#92;&quot;hello-markdown&#92;&quot;&gt;Hello, Markdown!&lt;/h1&gt;&#92;n&lt;span class=&#92;&quot;paragraph&#92;&quot;&gt;This is a paragsraph.&lt;/span&gt;&#92;n&lt;div class=&#92;&quot;language-python3 codehilite&#92;&quot;&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class=&#92;&quot;n&#92;&quot;&gt;mo&lt;/span&gt;&lt;span class=&#92;&quot;o&#92;&quot;&gt;.&lt;/span&gt;&lt;span class=&#92;&quot;n&#92;&quot;&gt;md&lt;/span&gt;&lt;span class=&#92;&quot;p&#92;&quot;&gt;(&lt;/span&gt;&#92;n&lt;span class=&#92;&quot;w&#92;&quot;&gt; &lt;/span&gt;&lt;span class=&#92;&quot;sd&#92;&quot;&gt;&amp;#39;&amp;#39;&amp;#39;&lt;/span&gt;&#92;n&lt;span class=&#92;&quot;sd&#92;&quot;&gt; # Hello, Markdown!&lt;/span&gt;&#92;n&#92;n&lt;span class=&#92;&quot;sd&#92;&quot;&gt; This is a paragraph.&lt;/span&gt;&#92;n&lt;span class=&#92;&quot;sd&#92;&quot;&gt; &amp;#39;&amp;#39;&amp;#39;&lt;/span&gt;&#92;n&lt;span class=&#92;&quot;p&#92;&quot;&gt;)&lt;/span&gt;&#92;n&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/span&gt;&quot;'></marimo-mime-renderer>
+ </marimo-cell-output>
+ <marimo-cell-code hidden>%0Aimport%20marimo%20as%20mo%0Amo.md(%0A%20%20%20%20%22%22%22%0A%20%20%20%20%23%20Hello%2C%20Markdown!%0A%0A%20%20%20%20This%20is%20a%20paragsraph.%0A%0A%20%20%20%20%60%60%60python3%0A%20%20%20%20mo.md(%0A%20%20%20%20%20%20%20%20'''%0A%20%20%20%20%20%20%20%20%23%20Hello%2C%20Markdown!%0A%0A%20%20%20%20%20%20%20%20This%20is%20a%20paragraph.%0A%20%20%20%20%20%20%20%20'''%0A%20%20%20%20)%0A%20%20%20%20%60%60%60%0A%20%20%20%20%22%22%22%0A)%0A</marimo-cell-code>
+</marimo-island>
\ No newline at end of file
diff --git a/tests/_output/formatters/test_structures.py b/tests/_output/formatters/test_structures.py
index 34debcf61c..1c6d57a09b 100644
--- a/tests/_output/formatters/test_structures.py
+++ b/tests/_output/formatters/test_structures.py
@@ -110,7 +110,7 @@ def test_format_structure_nested_with_html() -> None:
assert get_and_format(nested_structure) == (
"application/json",
- f'[1, "text/html:{escape(_markdown.text)}", "text/html:{escape(_slider.text)}"]',
+ f'[1, "text/markdown:{escape(_markdown.text)}", "text/html:{escape(_slider.text)}"]',
)
diff --git a/tests/_output/test_hypertext.py b/tests/_output/test_hypertext.py
index 4c662444ca..6177dba9a4 100644
--- a/tests/_output/test_hypertext.py
+++ b/tests/_output/test_hypertext.py
@@ -5,7 +5,6 @@ import pytest
from marimo._dependencies.dependencies import DependencyManager
from marimo._output.hypertext import (
Html,
- _js,
patch_html_for_non_interactive_output,
)
from marimo._plugins.ui._impl.batch import batch as batch_plugin
@@ -30,6 +29,15 @@ def test_html_mime():
}
+def test_html_mime_with_script():
+ # Test that Html returns text/html even with script tags
+ # This is expected behavior - Html is for raw HTML that may include scripts
+ html = Html('<p>Test</p><script>console.log("hello")</script>')
+ mime_type, content = html._mime_()
+ assert mime_type == "text/html"
+ assert '<script>console.log("hello")</script>' in content
+
+
def test_html_format():
html = Html("<p>\n Hello\n</p>")
assert f"{html}" == "<p> Hello </p>"
@@ -115,11 +123,6 @@ def test_html_style():
assert "font-size:16px" in styled.text
-def test_js():
- js_html = _js("console.log('Hello');")
- assert js_html.text == "<script>console.log('Hello');</script>"
-
-
# Add more tests as needed for edge cases and other functionalities
@@ -160,23 +163,6 @@ def test_html_style_empty_dict():
assert styled.text == "<div><p>No Style</p></div>"
-def test_js_empty():
- js_html = _js("")
- assert js_html.text == "<script></script>"
-
-
-def test_js_multiple_lines():
- js_code = """
- console.log('Line 1');
- console.log('Line 2');
- """
- js_html = _js(js_code)
- assert "<script>" in js_html.text
- assert "console.log('Line 1');" in js_html.text
- assert "console.log('Line 2');" in js_html.text
- assert "</script>" in js_html.text
-
-
def test_html_repr_html():
html = Html("<p>Hello</p>")
assert html._repr_html_() == "<p>Hello</p>"
diff --git a/tests/_output/test_md.py b/tests/_output/test_md.py
index 5d2a7a10af..2e09d80d02 100644
--- a/tests/_output/test_md.py
+++ b/tests/_output/test_md.py
@@ -449,6 +449,29 @@ def test_md_format():
assert f"{md}" == input_text
+def test_md_mime_type():
+ # Test that _md returns text/markdown mime type for proper sanitization
+ input_text = "This is **bold** and this is _italic_."
+ md = _md(input_text)
+ mime_type, content = md._mime_()
+ # Has markdown mime type so the frontend knows to sanitize it
+ assert mime_type == "text/markdown"
+ # Content should be the rendered HTML
+ assert "<strong>bold</strong>" in content
+ assert "<em>italic</em>" in content
+
+
+def test_md_mime_type_with_script():
+ # Test that _md returns text/markdown even with potentially dangerous content
+ # The frontend will sanitize it
+ input_text = "# Title\n\nSome text"
+ md = _md(input_text)
+ # Has markdown mime type so the frontend knows to sanitize it
+ mime_type, content = md._mime_()
+ assert mime_type == "text/markdown"
+ assert "Title" in content
+
+
@patch("marimo._runtime.output")
def test_latex_via_path(output: MagicMock, tmp_path: Path) -> None:
filename = tmp_path / "macros.tex"
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index f69d004144..576fc3ef16 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -3445,7 +3445,7 @@ class TestMarkdownHandling:
output_op = output_ops[0]
assert output_op.output.channel == CellChannel.OUTPUT
- assert output_op.output.mimetype == "text/html"
+ assert output_op.output.mimetype == "text/markdown"
assert "Hello World" in output_op.output.data
assert "<h1" in output_op.output.data # Should be rendered as HTML
assert output_op.status == "idle"
diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.py
index 6f8534b356..c47e6184e8 100644
--- a/tests/_server/test_sessions.py
+++ b/tests/_server/test_sessions.py
@@ -15,6 +15,8 @@ from textwrap import dedent
from typing import Any, Callable, TypeVar
from unittest.mock import MagicMock
+import pytest
+
from marimo._ast.app import App, InternalApp
from marimo._ast.app_config import _AppConfig
from marimo._config.manager import (
@@ -436,6 +438,7 @@ def test_session_with_kiosk_consumers() -> None:
assert session.room.main_consumer is None
@save_and_restore_main
async def test_session_manager_file_watching(tmp_path: Path) -> None:
# Create a temporary file