:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(notebooks): validate embed urls and isolate framed content (#102829)
Marius Andra845af1349af1
diff --git a/docs/internal/generated-notebook-widgets.md b/docs/internal/generated-notebook-widgets.mdindex 7cbd5d434aa6..12c0ffcb36d2 100644--- a/docs/internal/generated-notebook-widgets.md+++ b/docs/internal/generated-notebook-widgets.md@@ -151,6 +151,11 @@ The generated-code trust flow works as follows:Exact-build execution choices are stored in the browser, partitioned by PostHog user ID. Generated widgets are not rendered in publicly shared notebooks. This client-side consent state is a user-experience boundary; server authorization remains the data boundary.+Ordinary `<Embed>` blocks accept absolute HTTP or HTTPS URLs.+Public sharing removes invalid embed sources before serving notebook markdown.+Embed frames run without same-origin access, including when an external URL redirects to the application origin.+Embedded pages that require cookies or browser storage may need to be opened directly.+After consent, the bridge exposes only the version’s declared dataframes through permission-checked endpoints. The Canvas CSP keeps `connect-src 'none'`, but iframe self-navigation can still transmit data. A clean automated review cannot prove arbitrary JavaScript safe, so dataframe access requires consent even when no findings were reported.There is intentionally no “trust widgets by this author” option. An author is not the sole authority over a collaborative notebook node: another editor can change its instructions, regenerate it, restore a version, or otherwise replace the artifact after the original author created it. Binding trust to an immutable build is stable; binding it to a mutable ownership label is not.diff --git a/frontend/src/lib/components/MarkdownNotebook/registry.test.tsx b/frontend/src/lib/components/MarkdownNotebook/registry.test.tsxnew file mode 100644index 000000000000..1abd3bb55750--- /dev/null+++ b/frontend/src/lib/components/MarkdownNotebook/registry.test.tsx@@ -0,0 +1,40 @@+import { render } from '@testing-library/react'++import { parseMarkdownNotebook } from './markdown'+import { getMarkdownNotebookDefaultRegistry } from './registry'++describe('markdown notebook embed rendering', () => {+ it.each([+ ['https://example.com/embed', 'https://example.com/embed'],+ ['http://localhost:8000/embed', 'http://localhost:8000/embed'],+ [' HTTPS://example.com/embed ', 'HTTPS://example.com/embed'],+ [`${window.location.origin}/embed`, `${window.location.origin}/embed`],+ ['javascript:void(0)', null],+ ['data:text/html,example', null],+ ['about:blank', null],+ ['//example.com/embed', null],+ ['/embed', null],+ ['https://', null],+ ['https://[invalid', null],+ ['https://example.com/a b', null],+ ['java\nscript:void(0)', null],+ ['', null],+ ])('validates and isolates the embed source %s', (src, expectedSrc) => {+ const document = parseMarkdownNotebook(`<Embed src=${JSON.stringify(src)} title="Example" />`)+ const node = document.nodes[0]+ if (node.type !== 'component') {+ throw new Error('Expected an embed component')+ }+ const { ViewComponent } = getMarkdownNotebookDefaultRegistry().components.Embed+ const { container } = render(+ <ViewComponent node={node} mode="view" updateProps={jest.fn()} deleteNode={jest.fn()} />+ )+ const iframe = container.querySelector('iframe')+ if (expectedSrc === null) {+ expect(iframe).toBeNull()+ } else {+ expect(iframe?.getAttribute('src')).toBe(expectedSrc)+ expect(iframe?.getAttribute('sandbox')).toBe('allow-scripts')+ }+ })+})diff --git a/frontend/src/lib/components/MarkdownNotebook/registry.tsx b/frontend/src/lib/components/MarkdownNotebook/registry.tsxindex 4777ee5f9365..79c0e3e70847 100644--- a/frontend/src/lib/components/MarkdownNotebook/registry.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/registry.tsx@@ -17,6 +17,7 @@ import {import { LemonButton, LemonInput, LemonTextArea } from '@posthog/lemon-ui'import { wasNotebookNodeJustInserted } from './freshlyInserted'+import { sanitizeNotebookLinkHref } from './markdown'import {NotebookComponentDefinition,NotebookComponentBlockNode,@@ -341,11 +342,11 @@ function ImageEdit({ node, updateProps }: NotebookComponentRenderProps): JSX.Ele}function EmbedView({ node }: NotebookComponentRenderProps): JSX.Element {- const src = typeof node.props.src === 'string' ? node.props.src : ''+ const src = typeof node.props.src === 'string' ? sanitizeNotebookLinkHref(node.props.src) : nullconst title = typeof node.props.title === 'string' ? node.props.title : 'Embedded content'return src ? (- <iframe className="MarkdownNotebook__embed" src={src} title={title} sandbox="allow-scripts allow-same-origin" />+ <iframe className="MarkdownNotebook__embed" src={src} title={title} sandbox="allow-scripts" />) : (<SummaryView node={node} mode="view" updateProps={() => {}} deleteNode={() => {}} />)diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeEmbed.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeEmbed.tsxindex 76a4fabee8d8..b88440ec491a 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeEmbed.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeEmbed.tsx@@ -3,6 +3,7 @@ import { useEffect, useMemo, useState } from 'react'import { LemonButton, LemonInput, SpinnerOverlay } from '@posthog/lemon-ui'+import { sanitizeNotebookLinkHref } from 'lib/components/MarkdownNotebook/markdown'import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'@@ -35,15 +36,8 @@ const Component = ({ attributes }: NotebookNodeProps<NotebookNodeEmbedAttributesconst [loaded, setLoaded] = useState(false)const validUrl = useMemo(() => {- // Check the src exists and is a valid URL beginning with http- if (!src || /^https?:\/\//.test(src) === false) {- return null- }- try {- return new URL(src)- } catch {- return null- }+ const sanitizedSrc = typeof src === 'string' ? sanitizeNotebookLinkHref(src) : null+ return sanitizedSrc ? new URL(sanitizedSrc) : null}, [src])useEffect(() => {@@ -67,7 +61,7 @@ const Component = ({ attributes }: NotebookNodeProps<NotebookNodeEmbedAttributesonLoad={() => {setLoaded(true)}}- sandbox="allow-scripts allow-same-origin allow-popups allow-forms"+ sandbox="allow-scripts allow-popups allow-forms"/>{!loaded ? <SpinnerOverlay /> : null}</>diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2RendererUI.test.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2RendererUI.test.tsxindex 0d0ce75afe20..afcfd8a75681 100644--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2RendererUI.test.tsx+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2RendererUI.test.tsx@@ -11,6 +11,7 @@ import { initKeaTests } from '~/test/init'import { AccessControlLevel } from '~/types'import { NotebookType } from '../types'+import { NOTEBOOK_MARKDOWN_REGISTRY } from './markdownNotebookRegistry'import { buildMarkdownNotebookContent } from './markdownNotebookV2'import { MarkdownNotebookV2 } from './MarkdownNotebookV2Renderer'import { Notebook } from './Notebook'@@ -77,6 +78,35 @@ describe('MarkdownNotebookV2Renderer UI', () => {jest.restoreAllMocks()})+ it.each([+ [`${window.location.origin}/embed`, `${window.location.origin}/embed`],+ ['https://example.com/embed', 'https://example.com/embed'],+ ['HTTPS://example.com/embed', 'https://example.com/embed'],+ [' https://example.com/embed ', 'https://example.com/embed'],+ ['https://example.com/a b', null],+ ['javascript:void(0)', null],+ ['data:text/html,example', null],+ ])('validates and isolates the production embed for %s', (src, expectedSrc) => {+ const { ViewComponent } = NOTEBOOK_MARKDOWN_REGISTRY.components.Embed+ const { container } = render(+ <BindLogic logic={notebookLogic} props={logic.props}>+ <ViewComponent+ node={{ id: 'embed-test', type: 'component', tagName: 'Embed', props: { src } }}+ mode="view"+ updateProps={jest.fn()}+ deleteNode={jest.fn()}+ />+ </BindLogic>+ )+ const iframe = container.querySelector('iframe')+ if (expectedSrc === null) {+ expect(iframe).toBeNull()+ } else {+ expect(iframe?.getAttribute('src')).toBe(expectedSrc)+ expect(iframe?.getAttribute('sandbox')).toBe('allow-scripts allow-popups allow-forms')+ }+ })+it('opens kernel info from the header control and closes markdown source', () => {const logicProps: NotebookLogicProps = { shortId: SHORT_ID, mode: 'notebook', cachedNotebook }const onDebugOpenChange = jest.fn()diff --git a/products/notebooks/backend/test/test_sharing.py b/products/notebooks/backend/test/test_sharing.pyindex 0a6804fa7b2f..922ebad033ea 100644--- a/products/notebooks/backend/test/test_sharing.py+++ b/products/notebooks/backend/test/test_sharing.py@@ -377,6 +377,34 @@ class TestFilterNotebookContentForSharing(TestCase):)),),+ *[+ (+ f"markdown_embed_src_{index}",+ _markdown_doc(f'<Embed src={json.dumps(src)} title="Example" height={{240}} />'),+ _markdown_doc(+ "<Embed height={240}"+ + (f" src={json.dumps(expected_src)}" if expected_src is not None else "")+ + ' title="Example" />'+ ),+ )+ for index, (src, expected_src) in enumerate(+ [+ ("https://example.com/embed", "https://example.com/embed"),+ ("http://localhost:8000/embed", "http://localhost:8000/embed"),+ (" HTTPS://example.com/embed ", "HTTPS://example.com/embed"),+ ("javascript:void(0)", None),+ ("data:text/html,example", None),+ ("about:blank", None),+ ("//example.com/embed", None),+ ("/embed", None),+ ("https://", None),+ ("https://[invalid", None),+ ("https://example.com/a b", None),+ ("java\nscript:void(0)", None),+ ("", None),+ ]+ )+ ],])def test_filter(self, _name: str, content: Any, expected: Any) -> None:@@ -486,6 +514,8 @@ class TestNotebookSharingConfiguration(APIBaseTest):'<Query query={{"kind":"SavedInsightNode","shortId":"abc123"}} />','<Python code="SECRET = true" />','<Chat messages={{["SECRET_CHAT"]}} />',+ '<Embed src="javascript:void(0)" title="Example" />',+ '<Embed src={"data:text/html,example"} />',])self.notebook.content = _doc(@@ -527,6 +557,8 @@ class TestNotebookSharingConfiguration(APIBaseTest):'<Query query={{"kind":"SavedInsightNode","shortId":"abc123"}} />',"<Python />","<Chat />",+ '<Embed title="Example" />',+ "<Embed />",]),},diff --git a/products/notebooks/backend/util.py b/products/notebooks/backend/util.pyindex 60f134a9bf3e..e50a40147651 100644--- a/products/notebooks/backend/util.py+++ b/products/notebooks/backend/util.py@@ -6,6 +6,9 @@ import hashlibfrom collections.abc import Iteratorfrom typing import Any+from django.core.exceptions import ValidationError+from django.core.validators import URLValidator+from posthog.dataclasses import frozen# Type aliases for TipTap editor nodes@@ -74,6 +77,7 @@ _MARKDOWN_ESCAPED_COMPONENT_START_REGEX = re.compile(r"^\\<[A-Z][A-Za-z0-9]*(\s|_MARKDOWN_INLINE_ESCAPABLE_CHARACTERS = frozenset("\\`*_~[]()<>#+-.|!")_MAX_MARKDOWN_COMPONENT_LINES = 1_000_MAX_MARKDOWN_COMPONENT_CHARACTERS = 256 * 1024+_validate_notebook_embed_src = URLValidator(schemes=["http", "https"])@frozen@@ -182,6 +186,12 @@ def _filter_supported_markdown_component_for_sharing(tag_name: str, raw: str) ->for prop_name, expected_type in supported_props.items():value = props.get(prop_name)if _is_markdown_component_prop_type(value, expected_type):+ if tag_name == "Embed" and prop_name == "src" and isinstance(value, str):+ value = value.strip()+ try:+ _validate_notebook_embed_src(value)+ except ValidationError:+ continuefiltered_props[prop_name] = valuereturn _serialize_markdown_component(tag_name, filtered_props)