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.

feat(canvas): add notebook artifact boundary (#91532)

Marius Andra8641ca543837
diff --git a/posthog/api/advanced_activity_logs/viewset.py b/posthog/api/advanced_activity_logs/viewset.py
index 33ad89235876..2537b90cf219 100644
--- a/posthog/api/advanced_activity_logs/viewset.py
+++ b/posthog/api/advanced_activity_logs/viewset.py
@@ -102,11 +102,10 @@ def restrict_loop_activity_for_org(queryset: QuerySet[ActivityLog], organization
def restrict_canvas_activity(queryset: QuerySet[ActivityLog], team_id: int, user) -> QuerySet[ActivityLog]:
- """Keep personal-channel canvases' metadata out of the team-wide activity feed.
+ """Keep Canvas metadata hidden by channel visibility or source policy out of the feed.
- Canvas activity is team-scoped in the log, but a canvas in a personal channel is
- owner-only (see `CanvasViewSet`). Restrict `Canvas`-scoped rows to canvases this
- user may actually see. Lazy import keeps the canvas product off this module's path.
+ Restrict `Canvas`-scoped rows to canvases this user may access through `CanvasViewSet`.
+ Lazy import keeps the canvas product off this module's path.
"""
from products.canvas.backend import activity_visibility as canvas_activity # noqa: PLC0415
@@ -116,12 +115,12 @@ def restrict_canvas_activity(queryset: QuerySet[ActivityLog], team_id: int, user
def restrict_canvas_activity_for_org(queryset: QuerySet[ActivityLog], organization_id, user) -> QuerySet[ActivityLog]:
"""Org-wide equivalent of `restrict_canvas_activity`. The org route has no single
- `team_id`, so deny other users' personal-channel canvas rows across the org. Canvases
- are soft-deleted, so their visibility stays computable without a persisted snapshot.
+ `team_id`, so deny canvases hidden by channel visibility or source policy across the
+ org. Canvases are soft-deleted, so their visibility stays computable without a snapshot.
"""
from products.canvas.backend import activity_visibility as canvas_activity # noqa: PLC0415
- hidden_ids = canvas_activity.hidden_personal_canvas_ids_for_org(organization_id, user)
+ hidden_ids = canvas_activity.hidden_canvas_ids_for_org(organization_id, user)
if not hidden_ids:
return queryset
return queryset.exclude(Q(scope="Canvas") & Q(item_id__in=hidden_ids))
diff --git a/posthog/settings/canvas.py b/posthog/settings/canvas.py
index a15cedcf8c9a..6a23e3e6df89 100644
--- a/posthog/settings/canvas.py
+++ b/posthog/settings/canvas.py
@@ -4,6 +4,8 @@ from posthog.settings.base_variables import BASE_DIR, TEST
from posthog.settings.utils import get_list
CANVAS_ARTIFACT_ORIGIN = os.getenv("CANVAS_ARTIFACT_ORIGIN", "").rstrip("/")
+# Optional dedicated keys. Artifact signing otherwise uses SECRET_KEY and its
+# fallbacks, so enabling the artifact origin does not require a second secret.
CANVAS_ARTIFACT_SIGNING_KEYS = get_list(os.getenv("CANVAS_ARTIFACT_SIGNING_KEYS", ""))
if TEST and not CANVAS_ARTIFACT_SIGNING_KEYS:
CANVAS_ARTIFACT_SIGNING_KEYS = ["canvas-artifact-development-key-32-bytes"]
diff --git a/products/canvas/backend/activity_visibility.py b/products/canvas/backend/activity_visibility.py
index 04465d7d1cf9..780124111e86 100644
--- a/products/canvas/backend/activity_visibility.py
+++ b/products/canvas/backend/activity_visibility.py
@@ -1,15 +1,15 @@
-"""Canvas activity-log visibility, mirroring products.tasks loops.
-
-Canvas activity rows are team-scoped in the log, but a canvas filed in a personal
-channel is owner-only (`CanvasViewSet` filters every action through the tasks
-facade's `visible_channels_q`). Without these filters a teammate with activity-log
-access could read another member's personal-canvas names, ids, and declared capabilities
-out of the team- or org-wide feed. Canvases are soft-deleted (the row persists), so
-visibility stays computable from the `Canvas` table without snapshotting context.
+"""Canvas activity-log visibility, mirroring Canvas API visibility.
+
+Canvas API visibility requires both an accessible channel and the standard source
+policy. The activity feed must apply the same rules or it can expose names, ids, and
+declared capabilities for personal or product-managed canvases. Canvases are
+soft-deleted, so visibility stays computable without snapshotting context.
"""
from uuid import UUID
+from django.db.models import Q
+
from posthog.models.user import User
from products.canvas.backend.models import Canvas
@@ -17,25 +17,32 @@ from products.tasks.backend.facade import api as tasks_facade
def visible_canvas_ids(team_id: int, user: User | None) -> set[str]:
- """Ids (as strings) of this team's canvases whose channel the user may see.
+ """Ids of this team's canvases that the ordinary Canvas API exposes to the user.
Used to restrict `Canvas`-scoped rows in the team activity feed; a canvas hidden
from `CanvasViewSet` must not leak its history here either. Includes soft-deleted
canvases so an owner still sees their deleted canvas's history.
"""
user_id = getattr(user, "id", None)
- canvases = Canvas.objects.for_team(team_id).filter(tasks_facade.visible_channels_q(user_id, relation="channel"))
+ canvases = Canvas.objects.for_team(team_id).filter(
+ tasks_facade.visible_channels_q(user_id, relation="channel"),
+ source_policy=Canvas.SOURCE_POLICY_STANDARD,
+ )
return {str(canvas_id) for canvas_id in canvases.values_list("id", flat=True)}
-def hidden_personal_canvas_ids_for_org(organization_id: str | UUID, user: User | None) -> set[str]:
- """Ids (as strings) of personal-channel canvases across an org NOT owned by `user`.
+def hidden_canvas_ids_for_org(organization_id: str | UUID, user: User | None) -> set[str]:
+ """Ids of canvases hidden by channel visibility or source policy across an org.
- The org-wide feed (org admins/owners) must still keep other people's personal
- canvases out. Cross-team by design, hence `unscoped()`.
+ Cross-team by design, hence `unscoped()`.
"""
user_id = getattr(user, "id", None)
- hidden = Canvas.objects.unscoped().filter(
- ~tasks_facade.visible_channels_q(user_id, relation="channel"), team__organization_id=organization_id
+ hidden = (
+ Canvas.objects.unscoped()
+ .filter(team__organization_id=organization_id)
+ .filter(
+ ~tasks_facade.visible_channels_q(user_id, relation="channel")
+ | ~Q(source_policy=Canvas.SOURCE_POLICY_STANDARD)
+ )
)
return {str(canvas_id) for canvas_id in hidden.values_list("id", flat=True)}
diff --git a/products/canvas/backend/artifacts.py b/products/canvas/backend/artifacts.py
index 4482880661ef..2d8cf77a2dc1 100644
--- a/products/canvas/backend/artifacts.py
+++ b/products/canvas/backend/artifacts.py
@@ -50,8 +50,13 @@ def _configured_artifact_host() -> str | None:
return origin.netloc.lower()
+def _artifact_signing_keys() -> list[str]:
+ configured = settings.CANVAS_ARTIFACT_SIGNING_KEYS
+ return configured or [settings.SECRET_KEY, *settings.SECRET_KEY_FALLBACKS]
+
+
def create_canvas_artifact_token(build: CanvasBuild) -> str | None:
- keys = settings.CANVAS_ARTIFACT_SIGNING_KEYS
+ keys = _artifact_signing_keys()
if not keys or (not settings.CANVAS_ARTIFACT_ORIGIN and not (settings.DEBUG or settings.TEST)):
return None
if not (settings.DEBUG or settings.TEST) and (len(keys[0]) < 32 or _configured_artifact_host() is None):
@@ -86,7 +91,7 @@ def create_canvas_artifact_url(build: CanvasBuild, artifact_path: str) -> str |
def _read_token(token: str) -> dict[str, Any]:
current_bucket = int(time.time() // ARTIFACT_TOKEN_BUCKET_SECONDS)
- for key in settings.CANVAS_ARTIFACT_SIGNING_KEYS:
+ for key in _artifact_signing_keys():
try:
value = signing.Signer(key=key, salt=ARTIFACT_TOKEN_SALT).unsign_object(token)
except signing.BadSignature:
diff --git a/products/canvas/backend/build_service.py b/products/canvas/backend/build_service.py
index 71848b8e6305..2bfe6703ecdb 100644
--- a/products/canvas/backend/build_service.py
+++ b/products/canvas/backend/build_service.py
@@ -36,6 +36,7 @@ import structlog
import posthoganalytics
from prometheus_client import Counter, Gauge, Histogram
+from posthog.dataclasses import frozen
from posthog.event_usage import groups
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.models.scoping import team_scope
@@ -70,6 +71,29 @@ MAX_ACTIVE_CANVAS_BUILDS_PER_TEAM = 20
MAX_PINNED_BUILDS_PER_CANVAS = 10
MAX_BUILD_ATTEMPTS = 3
+
+@frozen
+class SourceProjectUpload:
+ key: str
+ digest: str
+ size: int
+
+
+@frozen
+class PreparedSourceProjectPublish:
+ project: dict[str, Any]
+ source_upload: SourceProjectUpload
+ legacy_upload: SourceProjectUpload | None
+
+
+@frozen
+class SourceProjectPublishResult:
+ canvas: Canvas
+ version: CanvasSourceVersion
+ build: CanvasBuild
+ first_publish: bool
+
+
# Rollout gate: flagged-in teams dispatch builds to Temporal instead of the shared
# long_running Celery queue. Evaluation failure keeps the Celery path.
CANVAS_BUILDS_ON_TEMPORAL_FLAG = "canvas-builds-on-temporal"
@@ -441,27 +465,18 @@ def _dispatch_build_to_temporal(build: CanvasBuild) -> bool:
return True
-def publish_source_project(
+def prepare_source_project_publish(
canvas: Canvas,
*,
project: dict[str, Any],
- prompt: str | None,
- name: str | None,
has_expected_version: bool,
expected_version_id: str | None,
- task_id: UUID | None,
- created_by: User | None,
- was_impersonated: bool = False,
-) -> tuple[Canvas, CanvasSourceVersion, CanvasBuild, bool]:
- """Publish a validated project as the canvas's new head version.
-
- Upload-then-commit: the immutable source object goes up before the
- transaction, so a conflicting publish leaves at most an unreferenced
- upload. Writes the "published" activity-log entry here (not in the API
- layer) so every caller is audited and the capabilities diff is computed
- against the head this publish actually replaced. Returns (canvas,
- version, build, first_publish). Raises CanvasVersionConflict,
- CanvasBuildCapacityExceeded, or ObjectStorageError.
+) -> PreparedSourceProjectPublish:
+ """Upload a source project before the metadata transaction begins.
+
+ The commit path rechecks version and capacity constraints under locks, so
+ callers can stage storage work before entering a wider transaction without
+ weakening concurrency guarantees.
"""
# Lock-free fail-fast: reject a doomed publish before paying for the
# upload. Its answer can go stale before the commit transaction re-checks
@@ -476,14 +491,39 @@ def publish_source_project(
_assert_build_capacity(canvas.team_id)
key, digest, size = upload_source_project(canvas.team_id, canvas.id, project)
+ source_upload = SourceProjectUpload(key=key, digest=digest, size=size)
# A migrated canvas's pre-relational source must survive its first publish:
# it becomes a real parent version here so history (undo/revert) can reach
# it — otherwise nulling legacy_code below would discard the only copy.
# Same upload-then-commit posture as the main project.
- legacy_upload: tuple[str, str, int] | None = None
+ legacy_upload: SourceProjectUpload | None = None
if current_id is None and (canvas.legacy_code or "").strip():
- legacy_upload = upload_source_project(canvas.team_id, canvas.id, synthetic_source_project(canvas.legacy_code))
+ legacy_key, legacy_digest, legacy_size = upload_source_project(
+ canvas.team_id, canvas.id, synthetic_source_project(canvas.legacy_code)
+ )
+ legacy_upload = SourceProjectUpload(key=legacy_key, digest=legacy_digest, size=legacy_size)
+
+ return PreparedSourceProjectPublish(
+ project=project,
+ source_upload=source_upload,
+ legacy_upload=legacy_upload,
+ )
+
+
+def commit_source_project_publish(
+ canvas: Canvas,
+ *,
+ prepared: PreparedSourceProjectPublish,
+ prompt: str | None,
+ name: str | None,
+ has_expected_version: bool,
+ expected_version_id: str | None,
+ task_id: UUID | None,
+ created_by: User | None,
+ was_impersonated: bool = False,
+) -> SourceProjectPublishResult:
+ """Commit a prepared source project and advance the canvas head."""
with transaction.atomic(), team_scope(canvas.team_id):
canvas = _claim_canvas_head(
@@ -491,31 +531,30 @@ def publish_source_project(
)
first_publish = canvas.current_source_version_id is None and not (canvas.legacy_code or "").strip()
if (
- legacy_upload is not None
+ prepared.legacy_upload is not None
and canvas.current_source_version_id is None
and (canvas.legacy_code or "").strip()
):
- legacy_key, legacy_digest, legacy_size = legacy_upload
canvas.current_source_version = CanvasSourceVersion.objects.create(
team_id=canvas.team_id,
canvas=canvas,
- source_hash=legacy_digest,
- source_object_key=legacy_key,
- source_size=legacy_size,
+ source_hash=prepared.legacy_upload.digest,
+ source_object_key=prepared.legacy_upload.key,
+ source_size=prepared.legacy_upload.size,
prompt="Imported source",
)
version = CanvasSourceVersion.objects.create(
team_id=canvas.team_id,
canvas=canvas,
parent_version_id=canvas.current_source_version_id,
- source_hash=digest,
- source_object_key=key,
- source_size=size,
+ source_hash=prepared.source_upload.digest,
+ source_object_key=prepared.source_upload.key,
+ source_size=prepared.source_upload.size,
task_id=task_id,
prompt=prompt or None,
created_by=created_by,
- capabilities=project.get("capabilities") or {},
- component_meta=project.get("component"),
+ capabilities=prepared.project.get("capabilities") or {},
+ component_meta=prepared.project.get("component"),
)
build = _queue_build(version)
@@ -542,7 +581,45 @@ def publish_source_project(
detail=Detail(name=canvas.name, changes=changes),
)
- return canvas, version, build, first_publish
+ return SourceProjectPublishResult(
+ canvas=canvas,
+ version=version,
+ build=build,
+ first_publish=first_publish,
+ )
+
+
+def publish_source_project(
+ canvas: Canvas,
+ *,
+ project: dict[str, Any],
+ prompt: str | None,
+ name: str | None,
+ has_expected_version: bool,
+ expected_version_id: str | None,
+ task_id: UUID | None,
+ created_by: User | None,
+ was_impersonated: bool = False,
+) -> tuple[Canvas, CanvasSourceVersion, CanvasBuild, bool]:
+ """Upload and publish a validated project as the canvas's new head version."""
+ prepared = prepare_source_project_publish(
+ canvas,
+ project=project,
+ has_expected_version=has_expected_version,
+ expected_version_id=expected_version_id,
+ )
+ result = commit_source_project_publish(
+ canvas,
+ prepared=prepared,
+ prompt=prompt,
+ name=name,
+ has_expected_version=has_expected_version,
+ expected_version_id=expected_version_id,
+ task_id=task_id,
+ created_by=created_by,
+ was_impersonated=was_impersonated,
+ )
+ return result.canvas, result.version, result.build, result.first_publish
def publish_grid_layout(
diff --git a/products/canvas/backend/checks.py b/products/canvas/backend/checks.py
index 13d3ae105fb7..18a7c721f335 100644
--- a/products/canvas/backend/checks.py
+++ b/products/canvas/backend/checks.py
@@ -2,8 +2,8 @@
A half-configured artifact origin used to fail silently: every build would
succeed and then serve ``artifact_url: null``. These system checks make a
-misconfiguration fail the deploy instead. An entirely unset configuration is
-legal — it means artifact delivery is off (DEBUG/TEST fall back to SITE_URL).
+misconfiguration fail the deploy instead. An entirely unset origin is legal —
+it means artifact delivery is off (DEBUG/TEST fall back to SITE_URL).
"""
from typing import Any
@@ -17,18 +17,22 @@ def check_artifact_delivery_settings(app_configs: Any, **kwargs: Any) -> list[Er
if settings.DEBUG or settings.TEST:
return []
origin = settings.CANVAS_ARTIFACT_ORIGIN
- keys = settings.CANVAS_ARTIFACT_SIGNING_KEYS
- if not origin and not keys:
+ dedicated_keys = settings.CANVAS_ARTIFACT_SIGNING_KEYS
+ if not origin and not dedicated_keys:
return []
- from products.canvas.backend.artifacts import _configured_artifact_host # noqa: PLC0415
+ from products.canvas.backend.artifacts import ( # noqa: PLC0415 — Django app registry must be ready
+ _artifact_signing_keys,
+ _configured_artifact_host,
+ )
errors: list[Error] = []
+ keys = _artifact_signing_keys()
if not origin or not keys:
errors.append(
Error(
- "CANVAS_ARTIFACT_ORIGIN and CANVAS_ARTIFACT_SIGNING_KEYS must be set together — "
- "half-configured artifact delivery serves no artifacts.",
+ "Canvas artifact delivery needs CANVAS_ARTIFACT_ORIGIN and a signing key from "
+ "CANVAS_ARTIFACT_SIGNING_KEYS or SECRET_KEY.",
id="canvas.E001",
)
)
@@ -44,7 +48,7 @@ def check_artifact_delivery_settings(app_configs: Any, **kwargs: Any) -> list[Er
if invalid_key_positions:
errors.append(
Error(
- "Every CANVAS_ARTIFACT_SIGNING_KEY must be at least 32 characters; invalid position(s): "
+ "Every Canvas artifact signing key must be at least 32 characters; invalid position(s): "
+ ", ".join(invalid_key_positions),
id="canvas.E003",
)
diff --git a/products/canvas/backend/migrations/0016_canvas_source_policy.py b/products/canvas/backend/migrations/0016_canvas_source_policy.py
new file mode 100644
index 000000000000..70da1d08cfdb
--- /dev/null
+++ b/products/canvas/backend/migrations/0016_canvas_source_policy.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("canvas", "0015_remove_canvas_discussion_task_id"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="canvas",
+ name="source_policy",
+ field=models.CharField(db_default="standard", default="standard", max_length=32),
+ ),
+ ]
diff --git a/products/canvas/backend/migrations/max_migration.txt b/products/canvas/backend/migrations/max_migration.txt
index 1b0323acc08f..c67378cbd8db 100644
--- a/products/canvas/backend/migrations/max_migration.txt
+++ b/products/canvas/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0015_remove_canvas_discussion_task_id
+0016_canvas_source_policy
diff --git a/products/canvas/backend/models.py b/products/canvas/backend/models.py
index f4744680f3bb..d37c8bc27dbc 100644
--- a/products/canvas/backend/models.py
+++ b/products/canvas/backend/models.py
@@ -33,6 +33,10 @@ class Canvas(TeamScopedRootMixin, UUIDModel):
KIND_COMPONENT = "component"
KINDS = [KIND_FREEFORM, KIND_GRID, KIND_COMPONENT]
+ SOURCE_POLICY_STANDARD = "standard"
+ SOURCE_POLICY_NOTEBOOK_WIDGET = "notebook_widget"
+ SOURCE_POLICIES = [SOURCE_POLICY_STANDARD, SOURCE_POLICY_NOTEBOOK_WIDGET]
+
# db_constraint=False: a real FK constraint to the hot posthog_team table
# takes a parent lock during migration; scoping is enforced app-side.
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
@@ -41,6 +45,7 @@ class Canvas(TeamScopedRootMixin, UUIDModel):
name = models.CharField(max_length=400)
kind = models.CharField(max_length=16, default=KIND_FREEFORM)
+ source_policy = models.CharField(max_length=32, default=SOURCE_POLICY_STANDARD, db_default=SOURCE_POLICY_STANDARD)
# Short prose describing what the canvas is/does. For components this is
# the store-search text agents match against, so it should say what the
# widget shows and what its config controls.
diff --git a/products/canvas/backend/notebook_integration.py b/products/canvas/backend/notebook_integration.py
new file mode 100644
index 000000000000..0e0e0aa302dc
--- /dev/null
+++ b/products/canvas/backend/notebook_integration.py
@@ -0,0 +1,314 @@
+from typing import Any
+from uuid import UUID
+
+from posthog.dataclasses import frozen
+from posthog.models import User
+from posthog.storage.object_storage import ObjectStorageError
+
+from products.canvas.backend import build_service
+from products.canvas.backend.artifacts import create_canvas_artifact_url
+from products.canvas.backend.models import Canvas, CanvasBuild, CanvasSourceVersion
+from products.canvas.backend.source import has_errors, synthetic_source_project, validate_source_project
+from products.tasks.backend.facade import api as tasks_facade
+
+_NETWORK_DIAGNOSTICS = {"network_fetch", "network_xhr"}
+_LEGACY_FRAME_BRIDGE_START = "/* __POSTHOG_NOTEBOOK_BRIDGE_START__ */"
+_LEGACY_FRAME_BRIDGE_END = "/* __POSTHOG_NOTEBOOK_BRIDGE_END__ */"
+
+
+@frozen
+class CanvasGenerationState:
+ current_source_version_id: UUID | None
+ artifact_url: str | None
+ build_status: str | None
+ build_error: str | None
+ build_hash: str | None = None
+
+
+@frozen
+class NotebookCanvasVersion:
+ id: UUID
+ build_status: str | None
+ artifact_url: str | None
+ build_hash: str | None = None
+
+
+@frozen
+class PreparedNotebookCanvasSource:
+ canvas_id: UUID
+ expected_current_version_id: UUID | None
+ prompt: str
+ name: str
+ prepared: build_service.PreparedSourceProjectPublish
+
+
+class NotebookCanvasError(Exception):
+ pass
+
+
+class NotebookCanvasNotFoundError(NotebookCanvasError):
+ pass
+
+
+class NotebookCanvasVersionConflictError(NotebookCanvasError):
+ pass
+
+
+class NotebookCanvasBuildCapacityError(NotebookCanvasError):
+ pass
+
+
+class NotebookCanvasSourceInvalidError(NotebookCanvasError):
+ pass
+
+
+def create_notebook_canvas(*, team_id: int, user_id: int, channel_id: UUID, name: str, context: str) -> UUID:
+ if not tasks_facade.channel_exists(team_id, channel_id, user_id):
+ raise NotebookCanvasNotFoundError
+ return (
+ Canvas.objects.for_team(team_id)
+ .create(
+ team_id=team_id,
+ channel_id=channel_id,
+ name=name,
+ context=context,
+ created_by_id=user_id,
+ source_policy=Canvas.SOURCE_POLICY_NOTEBOOK_WIDGET,
+ )
+ .id
+ )
+
+
+def _source_project(source: str, input_names: list[str]) -> dict[str, Any]:
+ project = synthetic_source_project(source)
+ files = project["files"]
+ if isinstance(files, dict) and isinstance(index_html := files.get("index.html"), str):
+ files["index.html"] = index_html.replace(
+ "</head>",
+ "<style>html,body,#root{width:100%;height:100%;margin:0}</style></head>",
+ )
+ project["capabilities"] = {
+ "posthog": {
+ "insights": [],
+ "inlineQueries": False,
+ "captureEvents": [],
+ "state": ["user"],
+ "notebookFrames": list(input_names),
+ },
+ "network": {"origins": []},
+ }
+ return project
+
+
+def _strip_legacy_frame_bridge(source: str) -> str:
+ if source.startswith(_LEGACY_FRAME_BRIDGE_START):
+ _, separator, user_source = source.partition(_LEGACY_FRAME_BRIDGE_END)
+ if separator:
+ return user_source.removeprefix("\n\n")
+ return source
+
+
+def validate_notebook_canvas_source(source: str, input_names: list[str]) -> list[dict[str, Any]]:
+ return [
+ {**diagnostic, "severity": "error"} if diagnostic.get("code") in _NETWORK_DIAGNOSTICS else diagnostic
+ for diagnostic in validate_source_project(_source_project(source, input_names))
+ ]
+
+
+def prepare_notebook_canvas_source(
+ *,
+ team_id: int,
+ canvas_id: UUID,
+ user_id: int,
+ source: str,
+ input_names: list[str],
+ prompt: str,
+ name: str,
+ expected_current_version_id: UUID | None,
+) -> PreparedNotebookCanvasSource:
+ canvas = (
+ Canvas.objects.for_team(team_id)
+ .filter(id=canvas_id, deleted=False, source_policy=Canvas.SOURCE_POLICY_NOTEBOOK_WIDGET)
+ .first()
+ )
+ if canvas is None or not User.objects.filter(id=user_id).exists():
+ raise NotebookCanvasNotFoundError
+
+ project = _source_project(source, input_names)
+ if has_errors(validate_notebook_canvas_source(source, input_names)):
+ raise NotebookCanvasSourceInvalidError
+
+ try:
+ prepared = build_service.prepare_source_project_publish(
+ canvas,
+ project=project,
+ has_expected_version=True,
+ expected_version_id=str(expected_current_version_id) if expected_current_version_id else None,
+ )
+ except build_service.CanvasVersionConflict as error:
+ raise NotebookCanvasVersionConflictError from error
+ except build_service.CanvasBuildCapacityExceeded as error:
+ raise NotebookCanvasBuildCapacityError from error
+ except ObjectStorageError as error:
+ raise NotebookCanvasError from error
+ return PreparedNotebookCanvasSource(
+ canvas_id=canvas.id,
+ expected_current_version_id=expected_current_version_id,
+ prompt=prompt,
+ name=name,
+ prepared=prepared,
+ )
+
+
+def publish_prepared_notebook_canvas_source(
+ *, team_id: int, user_id: int, prepared: PreparedNotebookCanvasSource
+) -> UUID:
+ canvas = (
+ Canvas.objects.for_team(team_id)
+ .filter(id=prepared.canvas_id, deleted=False, source_policy=Canvas.SOURCE_POLICY_NOTEBOOK_WIDGET)
+ .first()
+ )
+ user = User.objects.filter(id=user_id).first()
+ if canvas is None or user is None:
+ raise NotebookCanvasNotFoundError
+ try:
+ result = build_service.commit_source_project_publish(
+ canvas,
+ prepared=prepared.prepared,
+ prompt=prepared.prompt,
+ name=prepared.name,
+ has_expected_version=True,
+ expected_version_id=(
+ str(prepared.expected_current_version_id) if prepared.expected_current_version_id else None
+ ),
+ task_id=None,
+ created_by=user,
+ )
+ except build_service.CanvasVersionConflict as error:
+ raise NotebookCanvasVersionConflictError from error
+ except build_service.CanvasBuildCapacityExceeded as error:
+ raise NotebookCanvasBuildCapacityError from error
+ except ObjectStorageError as error:
+ raise NotebookCanvasError from error
+ return result.version.id
+
+
+def list_notebook_canvas_versions(
+ *, team_id: int, canvas_id: UUID, version_ids: list[UUID] | None = None
+) -> list[NotebookCanvasVersion]:
+ canvas = (
+ Canvas.objects.for_team(team_id)
+ .filter(id=canvas_id, deleted=False, source_policy=Canvas.SOURCE_POLICY_NOTEBOOK_WIDGET)
+ .first()
+ )
+ if canvas is None:
+ raise NotebookCanvasNotFoundError
+ versions_queryset = CanvasSourceVersion.objects.for_team(team_id).filter(canvas_id=canvas.id, draft=False)
+ builds_queryset = CanvasBuild.objects.for_team(team_id).filter(canvas_id=canvas.id)
+ if version_ids is not None:
+ versions_queryset = versions_queryset.filter(id__in=version_ids)
+ builds_queryset = builds_queryset.filter(source_version_id__in=version_ids)
+ versions = list(versions_queryset.order_by("created_at"))
+ builds = builds_queryset.order_by("-created_at")
+ latest_builds: dict[UUID, CanvasBuild] = {}
+ latest_ready_builds: dict[UUID, CanvasBuild] = {}
+ for build_record in builds:
+ latest_builds.setdefault(build_record.source_version_id, build_record)
+ if build_record.status == CanvasBuild.STATUS_READY:
+ latest_ready_builds.setdefault(build_record.source_version_id, build_record)
+
+ result: list[NotebookCanvasVersion] = []
+ for version in versions:
+ current_build = latest_builds.get(version.id)
+ ready_build = latest_ready_builds.get(version.id)
+ artifact_url: str | None = None
+ if (
+ ready_build is not None
+ and ready_build.artifact_object_prefix
+ and isinstance(ready_build.manifest, dict)
+ and isinstance(entry := ready_build.manifest.get("entryHtml"), str)
+ ):
+ artifact_url = create_canvas_artifact_url(ready_build, entry)
+ result.append(
+ NotebookCanvasVersion(
+ id=version.id,
+ build_status=current_build.status if current_build is not None else None,
+ artifact_url=artifact_url,
+ build_hash=ready_build.integrity if ready_build is not None else None,
+ )
+ )
+ return result
+
+
+def get_notebook_canvas_source(*, team_id: int, canvas_id: UUID, version_id: UUID | None = None) -> str:
+ canvas = (
+ Canvas.objects.for_team(team_id)
+ .filter(id=canvas_id, deleted=False, source_policy=Canvas.SOURCE_POLICY_NOTEBOOK_WIDGET)
+ .first()
+ )
+ if canvas is None:
+ raise NotebookCanvasNotFoundError
+ resolved_version_id = version_id or canvas.current_source_version_id
+ if resolved_version_id is None:
+ raise NotebookCanvasNotFoundError
+ version = (
+ CanvasSourceVersion.objects.for_team(team_id)
+ .filter(id=resolved_version_id, canvas_id=canvas.id, draft=False)
+ .first()
+ )
+ if version is None:
+ raise NotebookCanvasNotFoundError
+ try:
+ project = build_service.read_source_project(version)
+ except ObjectStorageError as error:
+ raise NotebookCanvasError from error
+ files = project.get("files")
+ source = files.get("src/canvas.tsx") if isinstance(files, dict) else None
+ if not isinstance(source, str):
+ raise NotebookCanvasSourceInvalidError
+ return _strip_legacy_frame_bridge(source)
+
+
+def get_canvas_generation_state(*, team_id: int, canvas_id: UUID) -> CanvasGenerationState | None:
+ canvas = (
+ Canvas.objects.for_team(team_id)
+ .select_related("published_build", "published_build__source_version")
+ .filter(id=canvas_id, deleted=False, source_policy=Canvas.SOURCE_POLICY_NOTEBOOK_WIDGET)
+ .first()
+ )
+ if canvas is None:
+ return None
+
+ current_build = (
+ CanvasBuild.objects.for_team(team_id)
+ .filter(canvas_id=canvas.id, source_version_id=canvas.current_source_version_id)
+ .order_by("-created_at")
+ .first()
+ if canvas.current_source_version_id
+ else None
+ )
+ published_build = canvas.published_build
+ artifact_url: str | None = None
+ if (
+ published_build is not None
+ and published_build.status == CanvasBuild.STATUS_READY
+ and published_build.artifact_object_prefix
+ and isinstance(published_build.manifest, dict)
+ and isinstance(entry := published_build.manifest.get("entryHtml"), str)
+ ):
+ artifact_url = create_canvas_artifact_url(published_build, entry)
+
+ build_error: str | None = None
+ if current_build is not None and isinstance(current_build.diagnostics, list):
+ for diagnostic in current_build.diagnostics:
+ if isinstance(diagnostic, dict) and isinstance(message := diagnostic.get("message"), str):
+ build_error = message[:1_000]
+ break
+
+ return CanvasGenerationState(
+ current_source_version_id=canvas.current_source_version_id,
+ artifact_url=artifact_url,
+ build_status=current_build.status if current_build else None,
+ build_error=build_error,
+ build_hash=published_build.integrity if published_build is not None else None,
+ )
diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.py
index 1bb30c852fff..cde0119773a6 100644
--- a/products/canvas/backend/presentation/views.py
+++ b/products/canvas/backend/presentation/views.py
@@ -288,7 +288,11 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
return super().list(request, *args, **kwargs)
def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
- queryset = queryset.filter(team_id=self.team_id, deleted=False)
+ queryset = queryset.filter(
+ team_id=self.team_id,
+ deleted=False,
+ source_policy=Canvas.SOURCE_POLICY_STANDARD,
+ )
user = self._request_user()
is_sandbox_authenticated = self._is_sandbox_authenticated(self.request)
if is_sandbox_authenticated:
diff --git a/products/canvas/backend/tests/test_artifact_tokens.py b/products/canvas/backend/tests/test_artifact_tokens.py
index 6e4766d5b5b9..3fea890546c8 100644
--- a/products/canvas/backend/tests/test_artifact_tokens.py
+++ b/products/canvas/backend/tests/test_artifact_tokens.py
@@ -14,6 +14,7 @@ from products.canvas.backend.artifacts import (
create_canvas_artifact_token,
create_canvas_artifact_url,
)
+from products.canvas.backend.checks import check_artifact_delivery_settings
def _claims(**overrides):
@@ -113,9 +114,49 @@ class TestCanvasArtifactTokens(SimpleTestCase):
with self.assertRaises(Http404):
canvas_artifact(RequestFactory().get("/"), token or "", "index.html")
- @override_settings(CANVAS_ARTIFACT_SIGNING_KEYS=[])
- def test_artifact_urls_fail_closed_without_signing_keys(self) -> None:
- self.assertIsNone(create_canvas_artifact_token(MagicMock()))
+ @override_settings(
+ DEBUG=False,
+ TEST=False,
+ CANVAS_ARTIFACT_ORIGIN="https://usercontent.example",
+ CANVAS_ARTIFACT_SIGNING_KEYS=[],
+ SECRET_KEY="new-django-signing-key-at-least-32-bytes-long",
+ SECRET_KEY_FALLBACKS=["old-django-signing-key-at-least-32-bytes-long"],
+ )
+ def test_artifact_urls_default_to_rotating_django_signing_keys(self) -> None:
+ build = MagicMock(
+ team_id=1,
+ canvas_id="00000000-0000-0000-0000-000000000001",
+ id="00000000-0000-0000-0000-000000000002",
+ )
+
+ token = create_canvas_artifact_token(build)
+
+ self.assertIsNotNone(token)
+ self.assertEqual(_read_token(token or "")["team_id"], 1)
+ previous_token = signing.Signer(
+ key="old-django-signing-key-at-least-32-bytes-long", salt=ARTIFACT_TOKEN_SALT
+ ).sign_object(_claims(bucket=int(time.time() // 3600)), compress=True)
+ self.assertEqual(_read_token(previous_token)["team_id"], 1)
+
+ @override_settings(
+ DEBUG=False,
+ TEST=False,
+ CANVAS_ARTIFACT_ORIGIN="https://usercontent.example",
+ CANVAS_ARTIFACT_SIGNING_KEYS=[],
+ SECRET_KEY="django-signing-key-at-least-32-bytes-long",
+ SECRET_KEY_FALLBACKS=[],
+ )
+ def test_production_check_accepts_django_signing_key_fallback(self) -> None:
+ self.assertEqual(check_artifact_delivery_settings(None), [])
+
+ @override_settings(
+ DEBUG=False,
+ TEST=False,
+ CANVAS_ARTIFACT_ORIGIN="",
+ CANVAS_ARTIFACT_SIGNING_KEYS=["dedicated-signing-key-at-least-32-bytes-long"],
+ )
+ def test_production_check_rejects_a_signing_key_without_an_origin(self) -> None:
+ self.assertIn("canvas.E001", [error.id for error in check_artifact_delivery_settings(None)])
@override_settings(
DEBUG=False,
diff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.py
index 28ff89bf1249..9aacc1c0bfe5 100644
--- a/products/canvas/backend/tests/test_canvas_api.py
+++ b/products/canvas/backend/tests/test_canvas_api.py
@@ -12,7 +12,7 @@ from parameterized import parameterized
from rest_framework import status
from rest_framework.test import APIClient
-from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.activity_logging.activity_log import ActivityLog, Detail, log_activity
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.scoping import team_scope
@@ -145,6 +145,24 @@ class TestCanvasCrud(CanvasAPIBaseTest):
response = self.client.get(f"/api/projects/{self.team.id}/canvases/")
assert {row["id"] for row in response.json()["results"]} == {canvas_id, other_id}
+ def test_notebook_widget_canvas_is_hidden_from_the_canvas_api(self):
+ with team_scope(self.team.id):
+ notebook_canvas = Canvas.objects.create(
+ team=self.team,
+ channel=self.channel,
+ name="Notebook widget",
+ created_by=self.user,
+ source_policy=Canvas.SOURCE_POLICY_NOTEBOOK_WIDGET,
+ )
+ base = f"/api/projects/{self.team.id}/canvases/{notebook_canvas.id}"
+
+ listed_ids = {row["id"] for row in self.client.get(f"/api/projects/{self.team.id}/canvases/").json()["results"]}
+
+ assert str(notebook_canvas.id) not in listed_ids
+ assert self.client.get(f"{base}/").status_code == status.HTTP_404_NOT_FOUND
+ assert self.client.get(f"{base}/source/").status_code == status.HTTP_404_NOT_FOUND
+ assert self._publish(str(notebook_canvas.id)).status_code == status.HTTP_404_NOT_FOUND
+
def test_can_file_canvas_to_another_visible_channel(self):
canvas_id = self._create_canvas()
with team_scope(self.team.id):
@@ -1045,10 +1063,21 @@ class TestCanvasActivityVisibility(CanvasAPIBaseTest):
)
return Canvas.objects.create(team_id=self.team.id, channel=channel, name="Private", created_by=owner)
+ def _notebook_widget(self) -> Canvas:
+ with team_scope(self.team.id):
+ return Canvas.objects.create(
+ team=self.team,
+ channel=self.channel,
+ name="Notebook widget",
+ created_by=self.user,
+ source_policy=Canvas.SOURCE_POLICY_NOTEBOOK_WIDGET,
+ )
+
def test_team_visible_ids_include_public_but_hide_others_personal_canvas(self):
other = self._create_user("[email protected]")
private = self._personal_canvas(self.user)
public_id = self._create_canvas(name="Public")
+ notebook_widget = self._notebook_widget()
owner_visible = activity_visibility.visible_canvas_ids(self.team.id, self.user)
other_visible = activity_visibility.visible_canvas_ids(self.team.id, other)
@@ -1056,15 +1085,41 @@ class TestCanvasActivityVisibility(CanvasAPIBaseTest):
assert {public_id, str(private.id)} <= owner_visible
assert public_id in other_visible
assert str(private.id) not in other_visible
+ assert str(notebook_widget.id) not in owner_visible
+ assert str(notebook_widget.id) not in other_visible
def test_org_hidden_ids_exclude_owner_but_include_other_members(self):
other = self._create_user("[email protected]")
private = self._personal_canvas(self.user)
+ notebook_widget = self._notebook_widget()
- assert str(private.id) not in activity_visibility.hidden_personal_canvas_ids_for_org(
- self.organization.id, self.user
- )
- assert str(private.id) in activity_visibility.hidden_personal_canvas_ids_for_org(self.organization.id, other)
+ assert str(private.id) not in activity_visibility.hidden_canvas_ids_for_org(self.organization.id, self.user)
+ assert str(private.id) in activity_visibility.hidden_canvas_ids_for_org(self.organization.id, other)
+ assert str(notebook_widget.id) in activity_visibility.hidden_canvas_ids_for_org(self.organization.id, self.user)
+ assert str(notebook_widget.id) in activity_visibility.hidden_canvas_ids_for_org(self.organization.id, other)
+
+ def test_team_activity_feed_hides_notebook_widget_rows(self):
+ public_id = self._create_canvas(name="Public")
+ notebook_widget = self._notebook_widget()
+ for item_id, name in ((public_id, "Public"), (str(notebook_widget.id), "Notebook widget")):
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ user=self.user,
+ was_impersonated=False,
+ item_id=item_id,
+ scope="Canvas",
+ activity="published",
+ detail=Detail(name=name),
+ force_save=True,
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/advanced_activity_logs/")
+
+ assert response.status_code == status.HTTP_200_OK
+ visible_canvas_ids = {row["item_id"] for row in response.json()["results"] if row["scope"] == "Canvas"}
+ assert public_id in visible_canvas_ids
+ assert str(notebook_widget.id) not in visible_canvas_ids
class TestCanvasDraftBuilds(CanvasAPIBaseTest):
diff --git a/products/canvas/backend/tests/test_cloud_builder.py b/products/canvas/backend/tests/test_cloud_builder.py
index 920e93b3d63b..ab9b90579fdf 100644
--- a/products/canvas/backend/tests/test_cloud_builder.py
+++ b/products/canvas/backend/tests/test_cloud_builder.py
@@ -81,6 +81,102 @@ class TestCanvasCloudBuilder(SimpleTestCase):
"canvasSdkVersion": "0.1.0",
}
+ def _notebook_project(self, source: str, frame_names: list[str] | None = None) -> dict[str, Any]:
+ project = self._project(source)
+ project["capabilities"] = {
+ "posthog": {
+ "insights": [],
+ "inlineQueries": False,
+ "captureEvents": [],
+ "state": ["user"],
+ "notebookFrames": frame_names or [],
+ },
+ "network": {"origins": []},
+ }
+ return project
+
+ def test_notebook_runtime_is_isolated_from_generated_source(self) -> None:
+ result = run_cloud_builder(self._notebook_project("void ph.readFrame"))
+
+ self.assertEqual(result["status"], "ready", result["diagnostics"])
+ runtime = next(file["content"] for file in result["files"] if file["path"] == "assets/canvas-runtime.js")
+ generated = "\n".join(
+ file["content"]
+ for file in result["files"]
+ if file["path"].endswith(".js") and file["path"] != "assets/canvas-runtime.js"
+ )
+ self.assertIn('type:"notebook-connect"', runtime)
+ self.assertIn("__posthog_notebook_frame__:", runtime)
+ self.assertIn("blockNavigation", runtime)
+ self.assertNotIn("notebook-connect", generated)
+
+ def test_notebook_runtime_keeps_navigation_blocked_after_source_mutates_event_prototype(self) -> None:
+ result = run_cloud_builder(self._notebook_project("void ph.readFrame"))
+ runtime = next(file["content"] for file in result["files"] if file["path"] == "assets/canvas-runtime.js")
+ harness = "\n".join(
+ [
+ "const listeners = {};",
+ "const timers = new Map();",
+ "let timerId = 0;",
+ "globalThis.window = globalThis;",
+ "globalThis.parent = { postMessage: () => {} };",
+ 'globalThis.document = { readyState: "complete", body: {}, head: { appendChild: () => {} }, addEventListener: () => {}, createElement: () => ({}) };',
+ 'globalThis.location = { hash: "" };',
+ "globalThis.MutationObserver = class { observe() {} };",
+ "globalThis.Element = class {};",
+ "globalThis.Event = class { preventDefault() { this.defaultPrevented = true; } };",
+ "globalThis.MessageEvent = class { constructor(_type, init) { Object.assign(this, init); } };",
+ "globalThis.navigation = { addEventListener: (type, fn) => { (listeners[type] ||= []).push(fn); } };",
+ "globalThis.addEventListener = (type, fn) => { (listeners[type] ||= []).push(fn); };",
+ "globalThis.dispatchEvent = () => {};",
+ "globalThis.setTimeout = (fn) => { timers.set(++timerId, fn); return timerId; };",
+ "globalThis.clearTimeout = (id) => { timers.delete(id); };",
+ runtime,
+ "Event.prototype.preventDefault = () => {};",
+ "const event = new Event();",
+ "for (const listener of listeners.navigate) listener(event);",
+ 'if (!event.defaultPrevented) { console.error("navigation was not prevented"); process.exit(1); }',
+ 'if (open("https://example.com") !== null) { console.error("open did not return null"); process.exit(1); }',
+ "process.exit(0);",
+ ]
+ )
+
+ process = subprocess.run([node_executable()], input=harness, capture_output=True, text=True, timeout=60)
+
+ self.assertEqual(process.returncode, 0, process.stderr or process.stdout)
+
+ def test_notebook_runtime_hides_state_and_enforces_allowed_frame_names(self) -> None:
+ result = run_cloud_builder(self._notebook_project("void ph.readFrame", ["public_df"]))
+ runtime = next(file["content"] for file in result["files"] if file["path"] == "assets/canvas-runtime.js")
+ harness = "\n".join(
+ [
+ "const listeners = {};",
+ "const timers = new Map();",
+ "let timerId = 0;",
+ "globalThis.window = globalThis;",
+ "globalThis.parent = { postMessage: () => {} };",
+ 'globalThis.document = { readyState: "complete", documentElement: { classList: { toggle: () => {} }, style: {} }, body: {}, head: { appendChild: () => {} }, addEventListener: () => {}, createElement: () => ({}) };',
+ 'globalThis.location = { hash: "" };',
+ "globalThis.MutationObserver = class { observe() {} };",
+ "globalThis.Element = class {};",
+ "globalThis.Event = class { preventDefault() {} };",
+ "globalThis.MessageEvent = class { constructor(_type, init) { Object.assign(this, init); } };",
+ "globalThis.addEventListener = (type, fn) => { (listeners[type] ||= []).push(fn); };",
+ "globalThis.dispatchEvent = () => {};",
+ "globalThis.setTimeout = (fn) => { timers.set(++timerId, fn); return timerId; };",
+ "globalThis.clearTimeout = (id) => { timers.delete(id); };",
+ runtime,
+ 'if ("state" in ph) { console.error("state remained public"); process.exit(1); }',
+ 'try { ph.readFrame("private_df"); console.error("private frame was allowed"); process.exit(1); } catch {}',
+ 'try { ph.readFrame("public_" + "df"); } catch { console.error("allowed frame was blocked"); process.exit(1); }',
+ "process.exit(0);",
+ ]
+ )
+
+ process = subprocess.run([node_executable()], input=harness, capture_output=True, text=True, timeout=60)
+
+ self.assertEqual(process.returncode, 0, process.stderr or process.stdout)
+
def test_builds_vanilla_typescript_with_the_shared_contract(self) -> None:
result = run_cloud_builder(self._project('document.querySelector("#root")!.textContent = "Hello"'))
diff --git a/products/canvas/backend/tests/test_notebook_integration.py b/products/canvas/backend/tests/test_notebook_integration.py
new file mode 100644
index 000000000000..0cae78fbcd05
--- /dev/null
+++ b/products/canvas/backend/tests/test_notebook_integration.py
@@ -0,0 +1,74 @@
+from posthog.test.base import APIBaseTest
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.models.scoping import team_scope
+
+from products.canvas.backend.models import Canvas
+from products.canvas.backend.notebook_integration import (
+ NotebookCanvasNotFoundError,
+ create_notebook_canvas,
+ validate_notebook_canvas_source,
+)
+from products.tasks.backend.models import Channel
+
+
+class TestNotebookCanvasSourceValidation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("location_variable", "const location = row.city"),
+ ("location_prop", "const marker = <Marker location={point} />"),
+ ("open_comment", "// click to open (details)"),
+ ("open_string", 'const label = "open (beta)"'),
+ ]
+ )
+ def test_accepts_navigation_words_that_do_not_navigate(self, _name: str, source: str) -> None:
+ diagnostics = validate_notebook_canvas_source(source, ["public_df"])
+
+ self.assertFalse([diagnostic for diagnostic in diagnostics if diagnostic["severity"] == "error"])
+
+ def test_accepts_a_direct_allowed_frame_read(self) -> None:
+ diagnostics = validate_notebook_canvas_source('void ph.readFrame("public_df")', ["public_df"])
+
+ self.assertFalse([diagnostic for diagnostic in diagnostics if diagnostic["severity"] == "error"])
+
+
+class TestNotebookCanvasCreation(APIBaseTest):
+ def test_rejects_another_users_personal_channel(self) -> None:
+ other_user = self._create_user("[email protected]")
+ with team_scope(self.team.id):
+ channel = Channel.objects.create(
+ team=self.team,
+ name="Other member",
+ channel_type=Channel.ChannelType.PERSONAL,
+ created_by=other_user,
+ )
+
+ with self.assertRaises(NotebookCanvasNotFoundError):
+ create_notebook_canvas(
+ team_id=self.team.id,
+ user_id=self.user.id,
+ channel_id=channel.id,
+ name="Widget",
+ context="Context",
+ )
+
+ self.assertFalse(Canvas.objects.unscoped().filter(channel_id=channel.id).exists())
+
+ def test_rejects_a_channel_from_another_team(self) -> None:
+ other_team = self.create_team_with_organization(self.organization)
+ with team_scope(other_team.id):
+ channel = Channel.objects.create(team=other_team, name="Other team", created_by=self.user)
+
+ with self.assertRaises(NotebookCanvasNotFoundError):
+ create_notebook_canvas(
+ team_id=self.team.id,
+ user_id=self.user.id,
+ channel_id=channel.id,
+ name="Widget",
+ context="Context",
+ )
+
+ self.assertFalse(Canvas.objects.unscoped().filter(channel_id=channel.id).exists())
diff --git a/products/canvas/packages/canvas_builder/build.mjs b/products/canvas/packages/canvas_builder/build.mjs
index 83bbc9806020..ff9784581558 100644
--- a/products/canvas/packages/canvas_builder/build.mjs
+++ b/products/canvas/packages/canvas_builder/build.mjs
@@ -23,11 +23,19 @@ const htmlAttribute = /([a-zA-Z][\w-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g
const forbiddenHtml = /(?:src|href)\s*=\s*["']\s*(javascript|data:text\/html|vbscript)/i
const extensions = ['', '.ts', '.tsx', '.js', '.jsx', '.css', '.json', '.svg', '.txt']
const runtimePath = 'assets/canvas-runtime.js'
+const notebookFrameKeyPrefix = '__posthog_notebook_frame__:'
// The host only delivers the MessagePort after the artifact iframe's load
// event, which fires after the app's module scripts have already run, so any
// ph.* call issued during mount lands before the port exists. Those messages
// queue (bounded, in case the host never connects) and flush on connect.
const runtime = `(()=>{const channel="posthog-canvas",pending=new Map,queued=[];let sequence=0,port;const post=(message)=>{const payload={channel,...message};if(port){port.postMessage(payload)}else if(queued.length<256){queued.push(payload)}};const call=(method,payload)=>new Promise((resolve,reject)=>{if(!port&&(method==="actionInvoke"||method==="agentRequest")){reject(new Error("Canvas actions require a user action"));return}const id=String(++sequence);const timer=setTimeout(()=>{pending.delete(id);const queuedIndex=queued.findIndex((message)=>message.type==="data-request"&&message.id===id);if(queuedIndex>-1)queued.splice(queuedIndex,1);reject(new Error("Canvas request timed out"));},30000);pending.set(id,{resolve,reject,timer});post({type:"data-request",id,method,payload});});const applyTheme=(theme)=>{if(theme!=="dark"&&theme!=="light")return;const dark=theme==="dark";document.documentElement.classList.toggle("dark",dark);document.documentElement.style.colorScheme=dark?"dark":"light";};const fragmentParams=new URLSearchParams(location.hash.slice(1));applyTheme(fragmentParams.get("theme"));let config={};try{const rawConfig=fragmentParams.get("config");if(rawConfig)config=Object.freeze(JSON.parse(rawConfig))}catch{config={}};const receive=(event)=>{if(event.data?.channel!==channel)return;if(event.data.type==="set-theme"){applyTheme(event.data.theme);return}if(event.data.type!=="data-response")return;const request=pending.get(event.data.id);if(!request)return;pending.delete(event.data.id);clearTimeout(request.timer);event.data.ok?request.resolve(event.data.result):request.reject(new Error(event.data.error??"Canvas request failed"));};const capture=(event,properties,distinctId)=>{const normalized=properties??{};let serialized;try{serialized=JSON.stringify(normalized)}catch{throw new Error("Canvas capture properties must be serializable")};if(typeof serialized!=="string"||serialized.length>16384)throw new Error("Canvas capture properties are too large");return call("capture",{event,properties:normalized,distinctId})};const openExternal=(value)=>{const url=new URL(value);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")))throw new Error("Canvas external URL is not allowed");post({type:"open-external",url:url.href})};window.ph={config,loadInsight:(shortId,options)=>call("loadInsight",{shortId,dateRange:options?.dateRange,variables:options?.variables,refresh:options?.refresh}),query:(query,params,options)=>call("query",typeof query==="string"?{hogql:query,params:params??{},refresh:options?.refresh}:{query,params:params??{},refresh:options?.refresh}),capture,openExternal,agent:{request:(prompt)=>call("agentRequest",{prompt})},state:{get:(key,opts)=>call("stateGet",{key,scope:opts?.scope||"user"}),set:(key,value,opts)=>call("stateSet",{key,value:value===undefined?null:value,scope:opts?.scope||"user"}),list:(opts)=>call("stateList",{scope:opts?.scope})},actions:{invoke:(verb,payload)=>call("actionInvoke",{verb,payload:payload??{}})}};addEventListener("message",(event)=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",receive);port.start();while(queued.length)port.postMessage(queued.shift());if(document.readyState!=="loading")post({type:"ready"});if(document.readyState==="complete")post({type:"rendered"});});addEventListener("error",(event)=>post({type:"error",message:event.message||"Canvas runtime error",stack:event.error?.stack}));addEventListener("unhandledrejection",(event)=>post({type:"error",message:event.reason instanceof Error?event.reason.message:String(event.reason),stack:event.reason instanceof Error?event.reason.stack:undefined}));const cspSeen=new Set();addEventListener("securitypolicyviolation",(event)=>{const directive=event.effectiveDirective||"unknown";if(cspSeen.has(directive))return;cspSeen.add(directive);post({type:"error",message:"SecurityPolicyViolationError: "+directive})});addEventListener("DOMContentLoaded",()=>post({type:"ready"}));addEventListener("load",()=>post({type:"rendered"}));})();`
+// Notebook source remains arbitrary JavaScript, and its separate AI review is advisory.
+// The cross-origin sandbox, CSP, host authorization, and frame allow-list are
+// load-bearing controls. Navigation interception is defense in depth: the Navigation
+// API covers Chromium, while click, submit, and window.open guards reduce accidental
+// navigation in other browsers.
+const notebookRuntime = (allowedFrameNames) =>
+ `(()=>{const channel="posthog-canvas",bridge=new MessageChannel,allowedFrames=new Set(${JSON.stringify(allowedFrameNames)}),stateGet=ph.state.get;delete ph.state;dispatchEvent(new MessageEvent("message",{data:{channel,type:"connect"},source:parent,ports:[bridge.port1]}));parent.postMessage({channel,type:"notebook-connect"},"*",[bridge.port2]);const preventDefault=Event.prototype.preventDefault;const blockNavigation=event=>preventDefault.call(event);globalThis.navigation?.addEventListener("navigate",blockNavigation);globalThis.addEventListener("click",event=>{if(event.target instanceof Element&&event.target.closest("a"))blockNavigation(event)},true);globalThis.addEventListener("submit",blockNavigation,true);Object.defineProperty(globalThis,"open",{value:()=>null,writable:false,configurable:false});Object.defineProperty(ph,"readFrame",{value:(name,options={})=>{if(typeof name!=="string"||!allowedFrames.has(name))throw new Error("Notebook dataframe is not available");return stateGet(${JSON.stringify(notebookFrameKeyPrefix)}+encodeURIComponent(name)+":"+(options.offset??0)+":"+(options.limit??100),{scope:"user"})},writable:false,configurable:false});})();`
// A published canvas runs the runtime baked into its artifact by this builder,
// while an unpublished one runs the desktop's sandbox document — two copies of
// the same selection behavior. The pair below is ported from the desktop's
@@ -540,7 +548,14 @@ async function buildCanvas(project) {
}
const cssPath = `assets/canvas-platform-${sha256(platformCss).slice(0, 10)}.css`
files.push(artifact(cssPath, platformCss))
- files.push(artifact(runtimePath, `${runtime}\n${selectionRuntime}\n${highlightRuntime}\n${keyboardRuntime}`))
+ const allowedNotebookFrames = project.capabilities?.posthog?.notebookFrames
+ const notebookBridge = Array.isArray(allowedNotebookFrames) ? `\n${notebookRuntime(allowedNotebookFrames)}` : ''
+ files.push(
+ artifact(
+ runtimePath,
+ `${runtime}${notebookBridge}\n${selectionRuntime}\n${highlightRuntime}\n${keyboardRuntime}`
+ )
+ )
const networkOrigins = project.capabilities?.network?.origins ?? []
const externalSources = networkOrigins.join(' ')
const projectCsp = externalSources
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 45bf2442cd67..1769f61c6cb6 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -7784,7 +7784,9 @@ def visible_tasks_q(user_id: int | None, *, relation: Literal["", "task"] = "")
def channel_exists(team_id: int, channel_id: str | UUID, user_id: int | None) -> bool:
"""Whether ``channel_id`` is a live channel in this team that the user may see."""
- return Channel.objects.filter(Channel.visible_to_q(user_id), id=channel_id, team_id=team_id, deleted=False).exists()
+ return (
+ Channel.objects.for_team(team_id).filter(Channel.visible_to_q(user_id), id=channel_id, deleted=False).exists()
+ )
def _visible_channel(channel_id: str | UUID, team_id: int, user_id: int | None) -> Channel | None: