: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: hide unsupported node content for shared notebooks (#59287)
Reece Jonesd74365a15ee6
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.pyindex 233caf7a44bc..b1b74d893336 100644--- a/posthog/api/sharing.py+++ b/posthog/api/sharing.py@@ -52,7 +52,7 @@ from products.dashboards.backend.api.dashboard import DashboardSerializerfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.notebooks.backend.api.notebook import NotebookSerializerfrom products.notebooks.backend.models import Notebook-from products.notebooks.backend.util import extract_inline_query_nodes+from products.notebooks.backend.util import extract_inline_query_nodes, filter_notebook_content_for_sharinglogger = structlog.get_logger(__name__)@@ -1077,6 +1077,14 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSeasset_title = resource.notebook.title or "Notebook"asset_description = ""notebook_data = NotebookSerializer(resource.notebook, context=context).data+ # Strip unsupported `ph-*` widget attrs before the document leaves the server — the+ # frontend `UnsupportedNodePlaceholder` is UI-only and the raw attrs would otherwise+ # ship to anonymous viewers.+ if isinstance(notebook_data.get("content"), dict):+ notebook_data["content"] = filter_notebook_content_for_sharing(notebook_data["content"])+ # `text_content` is a search-only plain-text projection that may include fragments of+ # the now-stripped nodes.+ notebook_data["text_content"] = Noneexported_data.update({"notebook": notebook_data})exported_data.update({"themes": get_themes_for_team(resource.team)})diff --git a/products/notebooks/backend/test/test_sharing.py b/products/notebooks/backend/test/test_sharing.pyindex e06ccb522358..9342c9d002a8 100644--- a/products/notebooks/backend/test/test_sharing.py+++ b/products/notebooks/backend/test/test_sharing.py@@ -11,6 +11,7 @@ from products.notebooks.backend.models import Notebookfrom products.notebooks.backend.util import (extract_inline_query_nodes,extract_referenced_insight_short_ids,+ filter_notebook_content_for_sharing,iter_prosemirror_nodes,)@@ -207,6 +208,98 @@ class TestExtractInlineQueryNodes(APIBaseTest):)+class TestFilterNotebookContentForSharing(APIBaseTest):+ @parameterized.expand(+ [+ ("none", None, None),+ ("not_a_dict", "not a doc", "not a doc"),+ (+ "builtin_nodes_pass_through",+ _doc(+ {"type": "paragraph", "content": [{"type": "text", "text": "hello"}]},+ {"type": "heading", "attrs": {"level": 1}, "content": [{"type": "text", "text": "h"}]},+ ),+ _doc(+ {"type": "paragraph", "content": [{"type": "text", "text": "hello"}]},+ {"type": "heading", "attrs": {"level": 1}, "content": [{"type": "text", "text": "h"}]},+ ),+ ),+ (+ "allow_listed_widgets_keep_attrs",+ _doc(+ {"type": "ph-image", "attrs": {"src": "x"}},+ {"type": "ph-latex", "attrs": {"content": "E=mc^2"}},+ {"type": "ph-embed", "attrs": {"src": "https://example.com"}},+ _saved_insight_query_node("abc123"),+ ),+ _doc(+ {"type": "ph-image", "attrs": {"src": "x"}},+ {"type": "ph-latex", "attrs": {"content": "E=mc^2"}},+ {"type": "ph-embed", "attrs": {"src": "https://example.com"}},+ _saved_insight_query_node("abc123"),+ ),+ ),+ (+ "unsupported_widget_attrs_stripped",+ _doc(+ {"type": "ph-python", "attrs": {"code": "SECRET"}},+ {"type": "ph-duck-sql", "attrs": {"code": "SELECT *", "duckExecution": {"tableData": [[1]]}}},+ {"type": "ph-recording", "attrs": {"id": "rec-1"}},+ {"type": "ph-feature-flag", "attrs": {"id": 42}},+ {"type": "ph-llm-trace", "attrs": {"id": "trace-1"}},+ ),+ _doc(+ {"type": "ph-python"},+ {"type": "ph-duck-sql"},+ {"type": "ph-recording"},+ {"type": "ph-feature-flag"},+ {"type": "ph-llm-trace"},+ ),+ ),+ (+ "unsupported_widget_child_content_dropped",+ _doc(+ {+ "type": "ph-zendesk-tickets",+ "attrs": {"query": "customer:acme"},+ "content": [{"type": "text", "text": "leaked"}],+ },+ ),+ _doc({"type": "ph-zendesk-tickets"}),+ ),+ (+ "nested_unsupported_widget_stripped",+ _doc(+ {+ "type": "blockquote",+ "content": [+ {"type": "paragraph", "content": [{"type": "text", "text": "keep"}]},+ {"type": "ph-python", "attrs": {"code": "SECRET"}},+ ],+ }+ ),+ _doc(+ {+ "type": "blockquote",+ "content": [+ {"type": "paragraph", "content": [{"type": "text", "text": "keep"}]},+ {"type": "ph-python"},+ ],+ }+ ),+ ),+ ]+ )+ def test_filter(self, _name: str, content: Any, expected: Any) -> None:+ self.assertEqual(filter_notebook_content_for_sharing(content), expected)++ def test_filter_does_not_mutate_input(self) -> None:+ original = _doc({"type": "ph-python", "attrs": {"code": "SECRET"}})+ snapshot = {"type": "doc", "content": [{"type": "ph-python", "attrs": {"code": "SECRET"}}]}+ filter_notebook_content_for_sharing(original)+ self.assertEqual(original, snapshot)++class TestNotebookSharingConfiguration(APIBaseTest):def setUp(self) -> None:super().setUp()@@ -252,14 +345,21 @@ class TestNotebookSharingConfiguration(APIBaseTest):response = self.client.get(self._sharing_url(short_id="nope"))self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)- def test_shared_notebook_renders_with_inlined_content(self) -> None:- # Mix supported (paragraph), saved-insight, and an unsupported node type. The frontend- # falls back to a placeholder for the latter — the backend still inlines whatever was saved- # so we don't lose data round-tripping through sharing.+ def test_shared_notebook_strips_unsupported_node_attrs(self) -> None:self.notebook.content = _doc({"type": "paragraph", "content": [{"type": "text", "text": "hi"}]},- {"type": "ph-recording", "attrs": {"id": "some-recording"}},+ {"type": "ph-image", "attrs": {"src": "https://example.com/x.png"}},+ {"type": "ph-python", "attrs": {"code": "SECRET = 'sk-...'"}},+ {+ "type": "ph-duck-sql",+ "attrs": {+ "code": "SELECT email, mrr FROM stripe.customers",+ "duckExecution": {"tableData": [["[email protected]", 12000]]},+ },+ },+ {"type": "ph-recording", "attrs": {"id": "01893f8c-some-recording"}},)+ self.notebook.text_content = "hi SECRET = 'sk-...' SELECT email, mrr FROM stripe.customers"self.notebook.save()self.client.patch(self._sharing_url(), {"enabled": True}, format="json")config = SharingConfiguration.objects.get(notebook=self.notebook, expires_at__isnull=True)@@ -274,6 +374,22 @@ class TestNotebookSharingConfiguration(APIBaseTest):self.assertEqual(body["notebook"]["short_id"], self.notebook.short_id)self.assertEqual(body["notebook"]["title"], "My notebook")+ nodes = body["notebook"]["content"]["content"]+ self.assertEqual(nodes[0], {"type": "paragraph", "content": [{"type": "text", "text": "hi"}]})+ self.assertEqual(nodes[1], {"type": "ph-image", "attrs": {"src": "https://example.com/x.png"}})+ self.assertEqual(nodes[2], {"type": "ph-python"})+ self.assertEqual(nodes[3], {"type": "ph-duck-sql"})+ self.assertEqual(nodes[4], {"type": "ph-recording"})++ # Defense in depth: catch any future field we forget to scrub.+ raw = response.content.decode()+ self.assertNotIn("SECRET", raw)+ self.assertNotIn("sk-...", raw)+ self.assertNotIn("stripe.customers", raw)+ self.assertNotIn("[email protected]", raw)+ self.assertNotIn("01893f8c-some-recording", raw)+ self.assertIsNone(body["notebook"]["text_content"])+def test_deleted_notebook_404s_on_shared_endpoint(self) -> None:self.client.patch(self._sharing_url(), {"enabled": True}, format="json")config = SharingConfiguration.objects.get(notebook=self.notebook, expires_at__isnull=True)diff --git a/products/notebooks/backend/util.py b/products/notebooks/backend/util.pyindex 6dcab8471557..18bc2a8b720c 100644--- a/products/notebooks/backend/util.py+++ b/products/notebooks/backend/util.py@@ -13,6 +13,45 @@ QUERY_NODE_TYPE = "ph-query"# QuerySchema kind that points at a saved insight by its short_id.SAVED_INSIGHT_NODE_KIND = "SavedInsightNode"+# Keep in sync with `SHARED_NOTEBOOK_SUPPORTED_NODE_TYPES` in+# `frontend/src/scenes/notebooks/Nodes/sharedNodeSupport.tsx`.+SHARED_NOTEBOOK_SUPPORTED_NODE_TYPES: frozenset[str] = frozenset(+ {+ "ph-image",+ "ph-latex",+ "ph-embed",+ "ph-query",+ }+)+++def filter_notebook_content_for_sharing(content: Any) -> Any:+ """Return a copy of a notebook's ProseMirror document with unsupported widget nodes redacted.++ Any ``ph-*`` node not in :data:`SHARED_NOTEBOOK_SUPPORTED_NODE_TYPES` has its ``attrs`` and+ child ``content`` stripped. The original ``type`` is preserved so the frontend's allow-list+ check still renders ``UnsupportedNodePlaceholder`` without leaking the original attrs to+ anonymous viewers. Built-in ProseMirror nodes pass through unchanged.+ """+ if not isinstance(content, dict):+ return content++ node_type = content.get("type")+ if (+ isinstance(node_type, str)+ and node_type.startswith("ph-")+ and node_type not in SHARED_NOTEBOOK_SUPPORTED_NODE_TYPES+ ):+ return {"type": node_type}++ filtered: dict[str, Any] = {k: v for k, v in content.items() if k != "content"}+ children = content.get("content")+ if isinstance(children, list):+ filtered["content"] = [filter_notebook_content_for_sharing(child) for child in children]+ elif "content" in content:+ filtered["content"] = children+ return filtered+def _coerce_query_attr(raw: Any) -> dict | None:"""Resolve a notebook ph-query node's `query` attribute to a dict.