: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
refactor(canvas): extract CanvasAccessMixin from CanvasViewSet (#95740)
Shy Alter0b132869acdd
diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.pyindex cde0119773a6..966d62b47105 100644--- a/products/canvas/backend/presentation/views.py+++ b/products/canvas/backend/presentation/views.py@@ -12,7 +12,7 @@ from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom rest_framework import status, viewsetsfrom rest_framework.decorators import action-from rest_framework.exceptions import NotFound+from rest_framework.exceptions import NotFound, PermissionDeniedfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.throttling import BaseThrottle, SimpleRateThrottle@@ -184,7 +184,95 @@ class CanvasActionInvokeThrottle(CanvasStateWriteThrottle):rate = "60/min"-class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):+class CanvasAccessMixin(TeamAndOrgViewSetMixin):+ """Team, channel, and sandbox visibility rules shared by every canvas-like resource."""++ scope_object_read_actions: list[str] = []++ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:+ queryset = queryset.filter(team_id=self.team_id, deleted=False)+ user = self._request_user()+ is_sandbox_authenticated = self._is_sandbox_authenticated(self.request)+ if is_sandbox_authenticated:+ sandbox_task_id = self._sandbox_task_id(self.request)+ if sandbox_task_id is None:+ return queryset.none()+ public_canvas_q = tasks_facade.visible_channels_q(None, relation="channel")+ if user is None:+ queryset = (+ queryset.filter(public_canvas_q)+ if self.action in self.scope_object_read_actions+ else queryset.none()+ )+ else:+ actor_canvas_q = Q(created_by_id=user.id) & tasks_facade.visible_channels_q(user.id, relation="channel")+ can_use_visible_canvas = self.action in [*self.scope_object_read_actions, "set_state"]+ queryset = queryset.filter(+ public_canvas_q | actor_canvas_q if can_use_visible_canvas else actor_canvas_q+ )+ else:+ # Channels are per-user for the personal kind: the facade's visibility+ # rule makes a canvas filed into someone else's personal channel+ # invisible (and unwritable) to everyone but its owner.+ queryset = queryset.filter(tasks_facade.visible_channels_q(user.id if user else None, relation="channel"))+ return queryset++ def _request_user(self) -> User | None:+ """The requesting real user, or None for anonymous/service principals."""+ user = self.request.user+ return user if isinstance(user, User) else None++ @staticmethod+ def _request_task_id(request: Request) -> UUID | None:+ """The publishing task's id, when the sandbox stamped one on the call."""+ raw_task_id = (request.headers.get("X-PostHog-Task-Id") or "").strip()+ try:+ return UUID(raw_task_id)+ except ValueError:+ return None++ def _sandbox_task_id(self, request: Request) -> UUID | None:+ """Return the calling sandbox's task when its header matches the OAuth binding."""+ task_id = self._request_task_id(request)+ if task_id is None or not self._is_sandbox_authenticated(request):+ return None+ authenticator = cast(OAuthAccessTokenAuthentication, request.successful_authenticator)+ if authenticator.access_token.sandbox_task_id != task_id:+ return None+ return task_id if tasks_facade.task_exists(task_id, self.team_id) else None++ @staticmethod+ def _is_sandbox_authenticated(request: Request) -> bool:+ """True when the request bears an OAuth token minted for a task sandbox —+ the credential a task sandbox (via the MCP server) calls this API with.++ The sandbox apps also issue the desktop app's interactive grants, so the application+ alone does not prove sandbox origin. Server-minted tokens carry either a task binding+ or the internal provenance scope. An unbound server token must still fail closed rather+ than inherit its user's Canvas visibility.+ """+ authenticator = request.successful_authenticator+ if not isinstance(authenticator, OAuthAccessTokenAuthentication):+ return False+ access_token = authenticator.access_token+ scopes = set((access_token.scope or "").split())+ if access_token.sandbox_task_id is None and "internal_run:read" not in scopes:+ return False+ application = access_token.application+ return application is not None and application.client_id in SANDBOX_OAUTH_APP_CLIENT_IDS++ def _validate_sandbox_channel(self, channel_id: UUID, task_id: UUID | None) -> None:+ if not self._is_sandbox_authenticated(self.request):+ return+ task_channel_id = tasks_facade.task_channel_id(task_id, self.team_id) if task_id else None+ if task_channel_id != channel_id:+ # Naming the right channel lets the agent recover in one step+ # and tell the user where the canvas will actually land.+ hint = f' Use the task\'s channel "{task_channel_id}".' if task_channel_id else ""+ raise PermissionDenied(f"This sandbox can file canvases only in its task's space.{hint}")+++class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):"""Canvases: agent-built sandboxed browser apps, filed into channels.Source is versioned per publish and built server-side; the canvas app@@ -288,35 +376,9 @@ 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,- source_policy=Canvas.SOURCE_POLICY_STANDARD,- )+ queryset = super().safely_get_queryset(queryset).filter(source_policy=Canvas.SOURCE_POLICY_STANDARD)user = self._request_user()is_sandbox_authenticated = self._is_sandbox_authenticated(self.request)- if is_sandbox_authenticated:- sandbox_task_id = self._sandbox_task_id(self.request)- if sandbox_task_id is None:- return queryset.none()- public_canvas_q = tasks_facade.visible_channels_q(None, relation="channel")- if user is None:- queryset = (- queryset.filter(public_canvas_q)- if self.action in self.scope_object_read_actions- else queryset.none()- )- else:- actor_canvas_q = Q(created_by_id=user.id) & tasks_facade.visible_channels_q(user.id, relation="channel")- can_use_visible_canvas = self.action in [*self.scope_object_read_actions, "set_state"]- queryset = queryset.filter(- public_canvas_q | actor_canvas_q if can_use_visible_canvas else actor_canvas_q- )- else:- # Channels are per-user for the personal kind: the facade's visibility- # rule makes a canvas filed into someone else's personal channel- # invisible (and unwritable) to everyone but its owner.- queryset = queryset.filter(tasks_facade.visible_channels_q(user.id if user else None, relation="channel"))if not is_sandbox_authenticated and self.action in self._CREATOR_ONLY_ACTIONS:if user is None:return queryset.none()@@ -358,16 +420,7 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):if not tasks_facade.channel_exists(self.team_id, channel_id, user.id if user else None):return Response({"detail": "Channel not found in this team."}, status=status.HTTP_400_BAD_REQUEST)sandbox_task_id = self._sandbox_task_id(request)- if self._is_sandbox_authenticated(request):- task_channel_id = tasks_facade.task_channel_id(sandbox_task_id, self.team_id) if sandbox_task_id else None- if task_channel_id != channel_id:- # Naming the right channel lets the agent recover in one step- # and tell the user where the canvas will actually land.- hint = f' Use the task\'s channel "{task_channel_id}".' if task_channel_id else ""- return Response(- {"detail": f"This sandbox can create canvases only in its task's space.{hint}"},- status=status.HTTP_403_FORBIDDEN,- )+ self._validate_sandbox_channel(channel_id, sandbox_task_id)canvas = Canvas.objects.create(team_id=self.team_id,channel_id=channel_id,@@ -431,16 +484,7 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):user = self._request_user()if not tasks_facade.channel_exists(self.team_id, channel_id, user.id if user else None):return Response({"detail": "Channel not found in this team."}, status=status.HTTP_400_BAD_REQUEST)- if self._is_sandbox_authenticated(request):- sandbox_task_id = self._sandbox_task_id(request)- task_channel_id = (- tasks_facade.task_channel_id(sandbox_task_id, self.team_id) if sandbox_task_id else None- )- if task_channel_id != channel_id:- return Response(- {"detail": "This sandbox can file canvases only in its task's space."},- status=status.HTTP_403_FORBIDDEN,- )+ self._validate_sandbox_channel(channel_id, self._sandbox_task_id(request))if channel_id != canvas.channel_id:record("channel", str(canvas.channel_id), str(channel_id))if canvas.pinned_at is not None:@@ -1815,30 +1859,6 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):request=self.request,)- def _request_user(self) -> User | None:- """The requesting real user, or None for anonymous/service principals."""- user = self.request.user- return user if isinstance(user, User) else None-- @staticmethod- def _request_task_id(request: Request) -> UUID | None:- """The publishing task's id, when the sandbox stamped one on the call."""- raw_task_id = (request.headers.get("X-PostHog-Task-Id") or "").strip()- try:- return UUID(raw_task_id)- except ValueError:- return None-- def _sandbox_task_id(self, request: Request) -> UUID | None:- """Return the calling sandbox's task when its header matches the OAuth binding."""- task_id = self._request_task_id(request)- if task_id is None or not self._is_sandbox_authenticated(request):- return None- authenticator = cast(OAuthAccessTokenAuthentication, request.successful_authenticator)- if authenticator.access_token.sandbox_task_id != task_id:- return None- return task_id if tasks_facade.task_exists(task_id, self.team_id) else None-def _announce_canvas_created(self, task_id: UUID | None, user: User | None, canvas: Canvas) -> None:"""Announce a canvas's first publish in the generating task's thread.@@ -1854,23 +1874,3 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):canvas_name=canvas.name or "Canvas",canvas_url=canvas_url(canvas),)-- @staticmethod- def _is_sandbox_authenticated(request: Request) -> bool:- """True when the request bears an OAuth token minted for a task sandbox —- the credential a task sandbox (via the MCP server) calls this API with.-- The sandbox apps also issue the desktop app's interactive grants, so the application- alone does not prove sandbox origin. Server-minted tokens carry either a task binding- or the internal provenance scope. An unbound server token must still fail closed rather- than inherit its user's Canvas visibility.- """- authenticator = request.successful_authenticator- if not isinstance(authenticator, OAuthAccessTokenAuthentication):- return False- access_token = authenticator.access_token- scopes = set((access_token.scope or "").split())- if access_token.sandbox_task_id is None and "internal_run:read" not in scopes:- return False- application = access_token.application- return application is not None and application.client_id in SANDBOX_OAUTH_APP_CLIENT_IDSdiff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.pyindex b9dd7106ff5e..3765b463ef7e 100644--- a/products/canvas/backend/tests/test_canvas_api.py+++ b/products/canvas/backend/tests/test_canvas_api.py@@ -221,7 +221,9 @@ class TestCanvasCrud(CanvasAPIBaseTest):)assert response.status_code == status.HTTP_403_FORBIDDEN- assert response.json()["detail"] == "This sandbox can file canvases only in its task's space."+ assert response.json()["detail"] == (+ f"This sandbox can file canvases only in its task's space. Use the task's channel \"{self.channel.id}\"."+ )assert Canvas.objects.unscoped().get(id=canvas_id).channel_id == self.channel.iddef test_personal_channel_canvases_are_invisible_to_other_users(self):