Skip to content

: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.

fix(notebooks): align validation across notebook saves (#116312)

Marius Andra5ac9899a5dd2
diff --git a/ee/hogai/tools/create_notebook/helpers.py b/ee/hogai/tools/create_notebook/helpers.py
index 32fea9be61eb..373fe44efdd5 100644
--- a/ee/hogai/tools/create_notebook/helpers.py
+++ b/ee/hogai/tools/create_notebook/helpers.py
@@ -144,7 +144,7 @@ async def save_notebook_to_db(
content=next_content,
title=title,
text_content=markdown_content,
- last_modified_by_id=user.id,
+ user=user,
)
if updated_notebook is None:
raise RuntimeError(f"Notebook {artifact.short_id} disappeared during content update")
@@ -208,7 +208,7 @@ async def save_notebook_to_db(
team.id,
artifact.short_id,
created_by_id=user.id,
- last_modified_by_id=user.id,
+ user=user,
title=title,
content=content,
text_content=text_content,
diff --git a/ee/hogai/tools/create_notebook/test/test_helpers.py b/ee/hogai/tools/create_notebook/test/test_helpers.py
index 96dc78ceed31..adab67af7a79 100644
--- a/ee/hogai/tools/create_notebook/test/test_helpers.py
+++ b/ee/hogai/tools/create_notebook/test/test_helpers.py
@@ -1,14 +1,25 @@
import json
+from datetime import timedelta
from posthog.test.base import BaseTest
-from unittest.mock import patch
+from unittest.mock import Mock, patch
+
+from django.utils import timezone
from asgiref.sync import async_to_sync
from parameterized import parameterized
from posthog.schema import MarkdownBlock, TrendsQuery, VisualizationMessage
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership
+from posthog.models.sharing_configuration import SharingConfiguration
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.notebooks.backend.facade.collab import apply_utf16_text_changes, markdown_crc
+from products.notebooks.backend.facade.content import build_markdown_notebook_content
+from products.notebooks.backend.facade.contracts import NotebookContentEditNotAllowed
from products.notebooks.backend.models import Notebook
from products.posthog_ai.backend.models.assistant import AgentArtifact, Conversation
@@ -369,3 +380,100 @@ class TestSaveNotebookToDb(BaseTest):
notebook.refresh_from_db()
self.assertEqual(notebook.title, "Protected title")
+
+ @parameterized.expand(
+ [
+ ("markdown_denied", "active", False, False, True),
+ ("markdown_allowed", "active", True, False, True),
+ ("unshared", "absent", False, False, True),
+ ("disabled", "disabled", False, False, True),
+ ("expired", "expired", False, False, True),
+ ("admin", "active", False, True, True),
+ ("without_entitlement", "active", False, False, False),
+ ]
+ )
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_save_checks_shared_notebook_content(
+ self,
+ _name: str,
+ sharing: str,
+ allowed: bool,
+ admin: bool,
+ entitled: bool,
+ _feature_enabled: Mock,
+ ) -> None:
+ self.organization.available_product_features = (
+ [{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}] if entitled else []
+ )
+ self.organization.save()
+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ membership.level = OrganizationMembership.Level.ADMIN if admin else OrganizationMembership.Level.MEMBER
+ membership.save()
+ view = DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="notebook_summary",
+ query={"kind": "HogQLQuery", "query": "SELECT 7 AS total"},
+ columns={"total": "Integer"},
+ )
+ AccessControl.objects.create(
+ team=self.team,
+ resource="warehouse_view",
+ resource_id=str(view.id),
+ access_level="viewer" if allowed else "none",
+ )
+ parent = self._create_notebook_parent("nsav")
+ original_content = build_markdown_notebook_content("Original")
+ notebook = Notebook.objects.create(
+ team=self.team,
+ short_id=parent.short_id,
+ title="Original",
+ content=original_content,
+ text_content="Original",
+ created_by=self.user,
+ last_modified_by=self.user,
+ )
+ if sharing != "absent":
+ SharingConfiguration.objects.create(
+ team=self.team,
+ notebook=notebook,
+ enabled=sharing != "disabled",
+ expires_at=timezone.now() - timedelta(hours=1) if sharing == "expired" else None,
+ )
+ query = {
+ "kind": "DataTableNode",
+ "source": {"kind": "HogQLQuery", "query": "SELECT total FROM notebook_summary"},
+ }
+ next_markdown = '<Query nodeId="summary" query={' + json.dumps(query) + "} />"
+ original_version = notebook.version
+ original_modified = notebook.last_modified_at
+
+ with patch("ee.hogai.tools.create_notebook.helpers.collab.apublish_notebook_update") as publish:
+
+ def save() -> None:
+ async_to_sync(save_notebook_to_db)(
+ team=self.team,
+ user=self.user,
+ artifact=parent,
+ blocks=[],
+ title="Updated",
+ state_messages=[],
+ markdown_content=next_markdown,
+ )
+
+ if sharing == "active" and not allowed and not admin and entitled:
+ with self.assertRaisesRegex(NotebookContentEditNotAllowed, "notebook_summary"):
+ save()
+ notebook.refresh_from_db()
+ self.assertEqual(notebook.content, original_content)
+ self.assertEqual(notebook.title, "Original")
+ self.assertEqual(notebook.text_content, "Original")
+ self.assertEqual(notebook.version, original_version)
+ self.assertEqual(notebook.last_modified_at, original_modified)
+ publish.assert_not_awaited()
+ else:
+ save()
+ notebook.refresh_from_db()
+ self.assertEqual(notebook.title, "Updated")
+ self.assertNotEqual(notebook.content, original_content)
+ self.assertEqual(notebook.version, original_version + 1)
+ publish.assert_awaited_once()
diff --git a/ee/hogai/tools/create_notebook/test/test_tool.py b/ee/hogai/tools/create_notebook/test/test_tool.py
index 2a1281d69ca8..696e97ad5124 100644
--- a/ee/hogai/tools/create_notebook/test/test_tool.py
+++ b/ee/hogai/tools/create_notebook/test/test_tool.py
@@ -1,5 +1,5 @@
from posthog.test.base import BaseTest
-from unittest.mock import patch
+from unittest.mock import Mock, patch
from asgiref.sync import async_to_sync
from langchain_core.runnables import RunnableConfig
@@ -7,6 +7,12 @@ from parameterized import parameterized
from posthog.schema import HumanMessage, MaxNotebookContext, MaxUIContext
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership
+from posthog.models.sharing_configuration import SharingConfiguration
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.notebooks.backend.models import Notebook
from products.posthog_ai.backend.models.assistant import Conversation
@@ -212,7 +218,11 @@ class TestCreateNotebookTool(BaseTest):
assert agent_artifact is not None
assert notebook.short_id == agent_artifact.short_id
- def test_update_already_saved_notebook_auto_updates_db(self):
+ @parameterized.expand([("allowed", False), ("denied", True)])
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_update_already_saved_notebook_auto_updates_db(
+ self, _name: str, denied: bool, _feature_enabled: Mock
+ ) -> None:
# First create and save
_, create_artifact = async_to_sync(self.tool._arun_impl)(
title="Original",
@@ -220,14 +230,47 @@ class TestCreateNotebookTool(BaseTest):
save_to_notebook=True,
)
short_id = create_artifact.messages[1].content.split("short_id: ")[1].split(".")[0]
+ notebook = Notebook.objects.get(team=self.team, short_id=short_id)
+ next_content = "# Updated Content"
+ if denied:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ membership.level = OrganizationMembership.Level.MEMBER
+ membership.save()
+ DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="weekly_totals",
+ query={"kind": "HogQLQuery", "query": "SELECT 3 AS total"},
+ columns={"total": "Integer"},
+ )
+ AccessControl.objects.create(team=self.team, resource="warehouse_objects", access_level="none")
+ SharingConfiguration.objects.create(team=self.team, notebook=notebook, enabled=True)
+ next_content = (
+ '<Query nodeId="totals" query={{"kind":"HogQLQuery","query":"SELECT total FROM weekly_totals"}} />'
+ )
# Now update without save_to_notebook -- should auto-update because already saved
- _, update_artifact = async_to_sync(self.tool._arun_impl)(
+ result, update_artifact = async_to_sync(self.tool._arun_impl)(
title="Updated",
- content="# Updated Content",
+ content=next_content,
artifact_id=short_id,
)
+ if denied:
+ assert update_artifact is None
+ assert "weekly_totals" in result
+ assert "notebook was not changed" in result
+ original_content = notebook.content
+ original_version = notebook.version
+ notebook.refresh_from_db()
+ assert notebook.title == "Original"
+ assert notebook.content == original_content
+ assert notebook.version == original_version
+ return
+
assert update_artifact is not None
tool_call_message = update_artifact.messages[1]
assert "updated" in tool_call_message.content.lower()
diff --git a/ee/hogai/tools/create_notebook/tool.py b/ee/hogai/tools/create_notebook/tool.py
index 9cfa080020de..7f9e7411ac1c 100644
--- a/ee/hogai/tools/create_notebook/tool.py
+++ b/ee/hogai/tools/create_notebook/tool.py
@@ -10,7 +10,7 @@ from posthog.models import Team, User
from posthog.sync import database_sync_to_async
from products.notebooks.backend.facade import api as notebooks
-from products.notebooks.backend.facade.contracts import NotebookCellLimitExceeded
+from products.notebooks.backend.facade.contracts import NotebookCellLimitExceeded, NotebookContentEditNotAllowed
from products.notebooks.backend.facade.widget_catalog import format_notebook_widget_catalog_for_agents
from ee.hogai.context.context import AssistantContextManager
@@ -226,7 +226,7 @@ class CreateNotebookTool(MaxTool):
"so it was not changed.",
None,
)
- except NotebookCellLimitExceeded as err:
+ except (NotebookCellLimitExceeded, NotebookContentEditNotAllowed) as err:
# Deterministic: the same save fails again, so say so rather than letting the
# model spend turns retrying it.
return (
diff --git a/products/notebooks/backend/facade/api.py b/products/notebooks/backend/facade/api.py
index ad2fb7feafb8..6f3acedf35f9 100644
--- a/products/notebooks/backend/facade/api.py
+++ b/products/notebooks/backend/facade/api.py
@@ -127,7 +127,7 @@ async def aupdate_notebook_content(
content: dict[str, Any],
title: str,
text_content: str | None,
- last_modified_by_id: int | None,
+ user: "User",
) -> contracts.NotebookData | None:
notebook = await logic.aupdate_notebook_content(
team_id,
@@ -135,7 +135,7 @@ async def aupdate_notebook_content(
content=content,
title=title,
text_content=text_content,
- last_modified_by_id=last_modified_by_id,
+ user=user,
)
return _to_notebook_data(notebook) if notebook is not None else None
@@ -145,7 +145,7 @@ async def aupsert_notebook(
short_id: str,
*,
created_by_id: int | None,
- last_modified_by_id: int | None,
+ user: "User",
title: str,
content: dict[str, Any],
text_content: str | None = None,
@@ -157,7 +157,7 @@ async def aupsert_notebook(
team_id,
short_id,
created_by_id=created_by_id,
- last_modified_by_id=last_modified_by_id,
+ user=user,
title=title,
content=content,
text_content=text_content,
diff --git a/products/notebooks/backend/facade/contracts.py b/products/notebooks/backend/facade/contracts.py
index f3ab843b79b6..9f09fa60ec5a 100644
--- a/products/notebooks/backend/facade/contracts.py
+++ b/products/notebooks/backend/facade/contracts.py
@@ -57,6 +57,10 @@ class NotebookMarkdownContentInvalid(Exception):
pass
+class NotebookContentEditNotAllowed(Exception):
+ pass
+
+
@dataclass(frozen=True)
class NotebookMarkdownComponent:
tag_name: str
diff --git a/products/notebooks/backend/logic.py b/products/notebooks/backend/logic.py
index b60d473e69f0..216b523ea1be 100644
--- a/products/notebooks/backend/logic.py
+++ b/products/notebooks/backend/logic.py
@@ -7,7 +7,7 @@ should import this module — cross-product callers go through ``facade.api``.
"""
from collections.abc import Iterable
-from typing import Any
+from typing import TYPE_CHECKING, Any
from uuid import UUID
from django.db import transaction
@@ -16,15 +16,40 @@ from django.utils import timezone
from asgiref.sync import sync_to_async
+from posthog.constants import AvailableFeature
from posthog.models import Team
from products.access_control.backend.facade.user_access_control import UserAccessControl
+from .facade.contracts import NotebookContentEditNotAllowed
from .markdown_conversion import get_markdown_notebook_markdown, is_markdown_notebook_content
from .markdown_migration import to_markdown_notebook_content
from .models import Notebook, ResourceNotebook
from .sql_v2_state import validate_cell_count
+if TYPE_CHECKING:
+ from posthog.models import User
+
+
+def _validate_shared_notebook_edit(user: "User", notebook: Notebook, content: dict[str, Any]) -> None:
+ from posthog.api.sharing_publish_gate import ( # noqa: PLC0415 — keep query runners off the facade import path
+ blocked_access_in_notebook_edit,
+ is_publicly_shared,
+ )
+
+ if not notebook.team.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL):
+ return
+ if UserAccessControl(user=user, team=notebook.team).is_organization_admin:
+ return
+ if not is_publicly_shared(notebook):
+ return
+ blocked = blocked_access_in_notebook_edit(user, notebook, content)
+ if blocked:
+ blocked_list = ", ".join(f"`{name}`" for name in blocked)
+ raise NotebookContentEditNotAllowed(
+ f"Can't save: you don't have access to {blocked_list}, and this notebook is publicly shared."
+ )
+
def _base_queryset(team_id: int, *, include_deleted: bool = False) -> Any:
qs = Notebook.objects.filter(team_id=team_id)
@@ -67,7 +92,7 @@ async def aupdate_notebook_content(
content: dict[str, Any],
title: str,
text_content: str | None,
- last_modified_by_id: int | None,
+ user: "User",
) -> Notebook | None:
notebook = await aget_notebook(team_id, short_id, include_deleted=True)
if notebook is None:
@@ -76,12 +101,13 @@ async def aupdate_notebook_content(
# entirely (it is a queryset update, so no save() hook or signal fires either), and it is
# how Max saves a notebook. A ceiling only the API respects is not a ceiling.
validate_cell_count(notebook.content, content)
+ await sync_to_async(_validate_shared_notebook_edit)(user, notebook, content)
await Notebook.objects.filter(pk=notebook.pk).aupdate(
content=content,
title=title,
text_content=text_content,
version=F("version") + 1,
- last_modified_by_id=last_modified_by_id,
+ last_modified_by_id=user.id,
last_modified_at=timezone.now(),
)
await notebook.arefresh_from_db()
@@ -93,7 +119,7 @@ async def aupsert_notebook(
short_id: str,
*,
created_by_id: int | None,
- last_modified_by_id: int | None,
+ user: "User",
title: str,
content: dict[str, Any],
text_content: str | None = None,
@@ -108,17 +134,18 @@ async def aupsert_notebook(
short_id=short_id,
defaults={
"created_by_id": created_by_id,
- "last_modified_by_id": last_modified_by_id,
+ "last_modified_by_id": user.id,
"title": title,
"content": content,
"text_content": text_content,
},
)
if not created:
+ await sync_to_async(_validate_shared_notebook_edit)(user, notebook, content)
notebook.content = content
notebook.title = title
notebook.version += 1
- notebook.last_modified_by_id = last_modified_by_id
+ notebook.last_modified_by_id = user.id
update_fields = ["content", "title", "version", "last_modified_by", "last_modified_at"]
if text_content is not None:
notebook.text_content = text_content
diff --git a/products/notebooks/backend/test/test_facade.py b/products/notebooks/backend/test/test_facade.py
index 2a7194ab81b5..8b49637ed51b 100644
--- a/products/notebooks/backend/test/test_facade.py
+++ b/products/notebooks/backend/test/test_facade.py
@@ -1,14 +1,23 @@
import pytest
from posthog.test.base import BaseTest
-from unittest.mock import patch
+from unittest.mock import Mock, patch
from django.apps import apps
+from asgiref.sync import async_to_sync
+from parameterized import parameterized
+
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership
+from posthog.models.sharing_configuration import SharingConfiguration
+
from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.access_control.backend.models.access_control import AccessControl
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.notebooks.backend import logic
from products.notebooks.backend.analytics import NotebookCreationSource
from products.notebooks.backend.facade import api, content
-from products.notebooks.backend.facade.contracts import NotebookCellLimitExceeded
+from products.notebooks.backend.facade.contracts import NotebookCellLimitExceeded, NotebookContentEditNotAllowed
from products.notebooks.backend.models import Notebook, ResourceNotebook
from products.notebooks.backend.sql_v2_state import MAX_NOTEBOOK_CELLS
@@ -138,6 +147,64 @@ class TestNotebooksFacadeAsync(BaseTest):
def _doc(self, text: str = "hi") -> dict:
return {"type": "doc", "content": [content.create_paragraph_with_text(text)]}
+ @parameterized.expand([("update",), ("upsert",)])
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_shared_content_validation_preserves_notebook(self, writer: str, _feature_enabled: Mock) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ membership.level = OrganizationMembership.Level.MEMBER
+ membership.save()
+ DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="daily_summary",
+ query={"kind": "HogQLQuery", "query": "SELECT 5 AS total"},
+ columns={"total": "Integer"},
+ )
+ AccessControl.objects.create(team=self.team, resource="warehouse_objects", access_level="none")
+ notebook = Notebook.objects.create(team=self.team, title="Original", content=self._doc())
+ SharingConfiguration.objects.create(team=self.team, notebook=notebook, enabled=True)
+ new_content = {
+ "type": "doc",
+ "content": [
+ {
+ "type": "ph-query",
+ "attrs": {
+ "nodeId": "daily",
+ "query": {"kind": "HogQLQuery", "query": "SELECT total FROM daily_summary"},
+ },
+ }
+ ],
+ }
+
+ with self.assertRaisesRegex(NotebookContentEditNotAllowed, "daily_summary"):
+ if writer == "update":
+ async_to_sync(api.aupdate_notebook_content)(
+ self.team.id,
+ notebook.short_id,
+ user=self.user,
+ title="Updated",
+ content=new_content,
+ text_content="Updated",
+ )
+ else:
+ async_to_sync(api.aupsert_notebook)(
+ self.team.id,
+ notebook.short_id,
+ user=self.user,
+ created_by_id=self.user.id,
+ title="Updated",
+ content=new_content,
+ text_content="Updated",
+ )
+ original_version = notebook.version
+ notebook.refresh_from_db()
+ self.assertEqual(notebook.content, self._doc())
+ self.assertEqual(notebook.title, "Original")
+ self.assertEqual(notebook.version, original_version)
+
@pytest.mark.asyncio
async def test_anotebook_exists_and_aget(self):
notebook = await Notebook.objects.acreate(team=self.team, title="async", content=self._doc())
@@ -153,7 +220,7 @@ class TestNotebooksFacadeAsync(BaseTest):
self.team.id,
"abc123",
created_by_id=self.user.id,
- last_modified_by_id=self.user.id,
+ user=self.user,
title="first",
content=self._doc("first"),
)
@@ -167,7 +234,7 @@ class TestNotebooksFacadeAsync(BaseTest):
self.team.id,
"abc123",
created_by_id=self.user.id,
- last_modified_by_id=self.user.id,
+ user=self.user,
title="second",
content=self._doc("second"),
)
@@ -187,7 +254,7 @@ class TestNotebooksFacadeAsync(BaseTest):
content=self._doc("updated"),
title="t2",
text_content="updated",
- last_modified_by_id=self.user.id,
+ user=self.user,
)
assert data is not None
self.assertEqual(data.title, "t2")
@@ -216,7 +283,7 @@ class TestNotebooksFacadeAsync(BaseTest):
content=self._cells_doc(MAX_NOTEBOOK_CELLS + 1),
title="t",
text_content="",
- last_modified_by_id=self.user.id,
+ user=self.user,
)
@pytest.mark.asyncio
@@ -228,7 +295,7 @@ class TestNotebooksFacadeAsync(BaseTest):
self.team.id,
"cap002",
created_by_id=self.user.id,
- last_modified_by_id=self.user.id,
+ user=self.user,
title="t",
content=self._cells_doc(MAX_NOTEBOOK_CELLS + 1),
)