: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
feat(conversations): add access control to support tickets (#70081)
Reece Jones957db693de6f
diff --git a/common/storybook/.storybook/app-context.ts b/common/storybook/.storybook/app-context.tsindex 8829f5ecc34c..10fb2a27e01c 100644--- a/common/storybook/.storybook/app-context.ts+++ b/common/storybook/.storybook/app-context.ts@@ -84,6 +84,7 @@ export const getStorybookAppContext = (): AppContext => ({sharing_configuration: 'manager',revenue_analytics: 'manager',survey: 'manager',+ ticket: 'manager',experiment: 'manager',export: 'manager',early_access_feature: 'manager',diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 3d16c915a21a..2cad1967767f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6935,9 +6935,9 @@ snapshots:scenes-app-settings-authentication-domains--one-unverified-domain--light:hash: v1.k794b7964.b1ae6dbc8feb673159fcc13f4a8fd5ee856c63ad1204e839a1b55ef70d109c81.W5sqRIJDHcdkKlYg4ghfwpbKS2FmlQKF_N-1C83h9Mgscenes-app-settings-environment--settings-environment-access-control--dark:- hash: v1.k794b7964.075bc140216002510c61cf29ee2b3877ca4d08bc7b6acb32d52147f70eea693a.EVC7gN9RyGMHLjpClT3REA2tP0XU-NLdfWzWi66JFZE+ hash: v1.k794b7964.cdbb2694b5d5524628e578f807f3282a0e458c45172c29b79e2b6e7c06eac09f.HqYn6cyhm9cm_fXbavd2nlYeqoTVNd7ODjvCMKlAsIcscenes-app-settings-environment--settings-environment-access-control--light:- hash: v1.k794b7964.d1717f298b33232ac22ab6de839baaa27fdfeffcded5250a4280b503068303dc.k3zUNlOwV7u8xkEk6HChmLZWfj1Ld2med7VbiF5HZQg+ hash: v1.k794b7964.e7b846c80dc983ad3f1b72b7bc40f4e892c9cc9d0af859a069f6e03d61362bb0.dFQvmM57ecntHp0lTNmpXgegTE3RedAWhId7EWSeKLwscenes-app-settings-environment--settings-environment-autocapture--dark:hash: v1.k794b7964.2183cf0082a1556d6df553572df4ab3813c96288a8b9a80e669c005908230c3e.-ybX8d6KyxaSa-yJDVccZm2CkK8Fl8qLSbw9jGhSIx4scenes-app-settings-environment--settings-environment-autocapture--light:diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsxindex 8a7e3adf9a32..f86b81f8e38e 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsx+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsx@@ -34,6 +34,7 @@ import {IconToolbar,IconTrends,IconWarning,+ IconSupport,} from '@posthog/icons'import { APIScopeObject } from '~/types'@@ -106,6 +107,8 @@ export function ScopeIcon(props: { scope: APIScopeObject }): JSX.Element | nullreturn <IconShare />case 'survey':return <IconMessage />+ case 'ticket':+ return <IconSupport />case 'tagger':return <IconList />case 'task':diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.tsindex 9b8f18280509..5139367a1605 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts@@ -1135,6 +1135,7 @@ export const accessControlLogic = kea<accessControlLogicType>([const resourceToRoute: Partial<Record<APIScopeObject, string>> = {warehouse_view: 'warehouse_saved_queries',early_access_feature: 'early_access_feature',+ ticket: 'conversations/tickets',heatmap: 'saved',replay_scanner: 'vision/scanners',}diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.tsindex b336a87c6386..379520cf2615 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts@@ -195,6 +195,7 @@ export const resourcesAccessControlLogic = kea<resourcesAccessControlLogicType>(AccessControlResourceType.ErrorTracking,AccessControlResourceType.ReplayScanner,AccessControlResourceType.Survey,+ AccessControlResourceType.Ticket,AccessControlResourceType.WebAnalytics,AccessControlResourceType.Toolbar,AccessControlResourceType.LlmPlayground,diff --git a/frontend/src/lib/utils/accessControlUtils.ts b/frontend/src/lib/utils/accessControlUtils.tsindex 62da9872e299..50b8be703a18 100644--- a/frontend/src/lib/utils/accessControlUtils.ts+++ b/frontend/src/lib/utils/accessControlUtils.ts@@ -94,6 +94,8 @@ export const pluralizeResource = (resource: APIScopeObject): string => {return 'LLM playground'} else if (resource === AccessControlResourceType.Workflow) {return 'workflows'+ } else if (resource === AccessControlResourceType.Ticket) {+ return 'support'} else if (resource === AccessControlResourceType.ReplayScanner) {// Covers both scanners and their scheduled summary actions — "replay vision" is the product name.return 'replay vision'diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex fdb44408fba9..85cf5b88bf73 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -233,6 +233,8 @@ export enum Scene {OrganizationPendingDeletion = 'OrganizationPendingDeletion',ProjectPendingDeletion = 'ProjectPendingDeletion',CustomerJourneyTemplates = 'CustomerJourneyTemplates',+ SupportTicketDetail = 'SupportTicketDetail',+ SupportSettings = 'SupportSettings',}export type SceneComponent<T> = (props: T) => JSX.Element | null@@ -389,6 +391,10 @@ export const sceneToAccessControlResourceType: Partial<Record<Scene, AccessContr[Scene.Survey]: AccessControlResourceType.Survey,[Scene.Surveys]: AccessControlResourceType.Survey,+ // Support (conversations)+ [Scene.SupportTickets]: AccessControlResourceType.Ticket,+ [Scene.SupportTicketDetail]: AccessControlResourceType.Ticket,+// Endpoints[Scene.EndpointsScene]: AccessControlResourceType.Endpoint,diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 52599453a963..6eb769c49557 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -293,6 +293,7 @@ export enum AccessControlResourceType {LlmPlayground = 'llm_playground',AiObservabilityClusters = 'ai_observability_clusters',Notebook = 'notebook',+ Ticket = 'ticket',SessionRecording = 'session_recording',SharingConfiguration = 'sharing_configuration',RevenueAnalytics = 'revenue_analytics',diff --git a/posthog/api/comments.py b/posthog/api/comments.pyindex 448b78e0bdef..29de65754804 100644--- a/posthog/api/comments.py+++ b/posthog/api/comments.py@@ -1,5 +1,6 @@-from typing import Any, cast+from typing import TYPE_CHECKING, Any, cast+from django.core import exceptions as django_exceptionsfrom django.db import transactionfrom django.db.models import Q, QuerySetfrom django.utils import timezone@@ -21,6 +22,31 @@ from posthog.models.comment.comment import activity_log_scope_forfrom posthog.models.comment.utils import produce_discussion_mention_events, send_mention_notificationsfrom posthog.tasks.email import send_discussions_mentioned+if TYPE_CHECKING:+ from posthog.rbac.user_access_control import UserAccessControl+++def _require_ticket_editor_access(+ *, team_id: int, item_id: str | None, user_access_control: "UserAccessControl"+) -> None:+ """Comments with scope=conversations_ticket are ticket messages (see TicketViewSet.reply) —+ enforce the same object-level RBAC here, since the generic comments API is the write path the+ Support UI actually uses and isn't gated by TicketViewSet's own access control."""+ if not item_id:+ return++ from products.conversations.backend.models.ticket import ( # noqa: PLC0415 — keeps the generic comments API decoupled from the conversations product, only imported for ticket-scoped writes+ Ticket,+ )++ try:+ ticket = Ticket.objects.get(team_id=team_id, id=item_id)+ except (Ticket.DoesNotExist, ValueError, django_exceptions.ValidationError):+ raise exceptions.ValidationError({"item_id": "Ticket not found"})++ if not user_access_control.check_access_level_for_object(ticket, required_level="editor"):+ raise exceptions.PermissionDenied("You do not have access to this ticket")+class CommentSerializer(serializers.ModelSerializer):def _extract_mentions_from_rich_content(self, rich_content: dict | None) -> list[int]:@@ -102,6 +128,25 @@ class CommentSerializer(serializers.ModelSerializer):if "is_task" in data and bool(data["is_task"]) != bool(instance.is_task):raise exceptions.ValidationError({"is_task": "Cannot change task state after creation."})+ # Check both the comment's persisted (scope, item_id) and the submitted target — so losing+ # ticket editor access after creation, and re-scoping a comment into or out of a ticket,+ # are all caught, not just fresh ticket-message creation.+ scopes_and_items = {+ (+ data.get("scope", instance.scope if instance else None),+ data.get("item_id", instance.item_id if instance else None),+ )+ }+ if instance:+ scopes_and_items.add((instance.scope, instance.item_id))+ for scope, item_id in scopes_and_items:+ if scope == "conversations_ticket":+ _require_ticket_editor_access(+ team_id=self.context["get_team"]().id,+ item_id=item_id,+ user_access_control=self.context["get_user_access_control"](),+ )+# Skip content validation when soft-deleting a commentis_deleting = data.get("deleted") is Trueif not is_deleting:@@ -227,6 +272,40 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVdef list(self, request, *args, **kwargs):return super().list(request, *args, **kwargs)+ def get_serializer_context(self) -> dict[str, Any]:+ context = super().get_serializer_context()+ context["get_user_access_control"] = lambda: self.user_access_control+ return context++ def _filter_ticket_scoped_queryset(self, queryset: QuerySet, item_id: str | None) -> QuerySet:+ """conversations_ticket comments are ticket messages — restrict them to tickets the+ caller has viewer access to, mirroring TicketViewSet's own object-level filtering."""+ from products.conversations.backend.models.ticket import ( # noqa: PLC0415 — keeps the generic comments API decoupled from the conversations product, only imported for ticket-scoped reads+ Ticket,+ )++ if item_id:+ try:+ ticket = Ticket.objects.get(team_id=self.team_id, id=item_id)+ except (Ticket.DoesNotExist, ValueError, django_exceptions.ValidationError):+ return queryset.none()+ if not self.user_access_control.check_access_level_for_object(ticket, required_level="viewer"):+ return queryset.none()+ return queryset++ # filter_queryset_by_access_level trusts the view to have enforced resource-level access+ # already, and this view is authorized as `comment` — so a caller denied the ticket resource+ # would otherwise get the unfiltered ticket queryset back here.+ if not self.user_access_control.check_access_level_for_resource(+ "ticket", "viewer"+ ) and not self.user_access_control.has_any_specific_access_for_resource("ticket", "viewer"):+ return queryset.none()++ visible_ticket_ids = self.user_access_control.filter_queryset_by_access_level(+ Ticket.objects.filter(team_id=self.team_id)+ ).values_list("id", flat=True)+ return queryset.filter(item_id__in=[str(ticket_id) for ticket_id in visible_ticket_ids])+def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:params = self.request.GET.dict()@@ -236,8 +315,11 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVif self.action != "partial_update" and params.get("deleted", "false") == "false":queryset = queryset.filter(deleted=False)- if params.get("scope"):- queryset = queryset.filter(scope=params.get("scope"))+ scope = params.get("scope")+ if scope:+ queryset = queryset.filter(scope=scope)+ if scope == "conversations_ticket":+ queryset = self._filter_ticket_scoped_queryset(queryset, params.get("item_id"))else:# Exclude conversations_ticket comments by default - they use rich content# from SupportEditor and should only be viewed in the conversations product@@ -299,6 +381,10 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVcomment = self.get_object()if not comment.is_task:raise exceptions.ValidationError("Only tasks can be marked complete")+ if comment.scope == "conversations_ticket":+ _require_ticket_editor_access(+ team_id=self.team_id, item_id=comment.item_id, user_access_control=self.user_access_control+ )with transaction.atomic():comment = Comment.objects.select_for_update().get(pk=comment.pk)if comment.completed_at is not None:@@ -321,6 +407,10 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVcomment = self.get_object()if not comment.is_task:raise exceptions.ValidationError("Only tasks can be reopened")+ if comment.scope == "conversations_ticket":+ _require_ticket_editor_access(+ team_id=self.team_id, item_id=comment.item_id, user_access_control=self.user_access_control+ )with transaction.atomic():comment = Comment.objects.select_for_update().get(pk=comment.pk)if comment.completed_at is None:diff --git a/posthog/api/test/test_comments.py b/posthog/api/test/test_comments.pyindex bd0cfad74c5d..6c342279afca 100644--- a/posthog/api/test/test_comments.py+++ b/posthog/api/test/test_comments.py@@ -8,10 +8,16 @@ from django.conf import settingsfrom parameterized import parameterizedfrom rest_framework import status+from posthog.models import Userfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.comment import Commentfrom posthog.models.comment.utils import build_comment_item_url, extract_plain_text_from_rich_content+from products.conversations.backend.models import Ticket+from products.conversations.backend.models.constants import Channel, Status++from ee.models.rbac.access_control import AccessControl+class TestComments(APIBaseTest, QueryMatchingTest):def _create_comment(self, data: dict | None = None) -> Any:@@ -571,6 +577,178 @@ class TestComments(APIBaseTest, QueryMatchingTest):assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED+class TestCommentsTicketAccessControl(APIBaseTest):+ """conversations_ticket comments are ticket messages read/written through this generic+ endpoint by the Support UI (not TicketViewSet) — object-level ticket RBAC must be+ enforced here too, or a denied member can read/write a ticket's messages directly."""++ def setUp(self) -> None:+ super().setUp()+ self.organization.available_product_features = [{"key": "access_control", "name": "Access control"}]+ self.organization.save()+ self.member = User.objects.create_and_join(self.organization, "[email protected]", "password")+ self.client.force_login(self.member)+ self.ticket = Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.WIDGET,+ widget_session_id="acl-session",+ distinct_id="acl-user",+ status=Status.OPEN,+ )+ AccessControl.objects.create(+ resource="ticket",+ resource_id=str(self.ticket.id),+ organization_member=self.member.organization_memberships.get(organization=self.organization),+ team=self.team,+ access_level="none",+ )+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="a private message",+ )++ def test_denied_member_cannot_list_ticket_messages(self) -> None:+ response = self.client.get(+ f"/api/projects/{self.team.id}/comments?scope=conversations_ticket&item_id={self.ticket.id}"+ )+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["results"] == []++ def test_denied_member_cannot_create_ticket_message(self) -> None:+ response = self.client.post(+ f"/api/projects/{self.team.id}/comments",+ {+ "content": "sneaking in a reply",+ "scope": "conversations_ticket",+ "item_id": str(self.ticket.id),+ "item_context": {"author_type": "support", "is_private": False},+ },+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert not Comment.objects.filter(item_id=str(self.ticket.id), content="sneaking in a reply").exists()++ def test_viewer_can_list_but_not_create_ticket_message(self) -> None:+ AccessControl.objects.filter(resource_id=str(self.ticket.id)).update(access_level="viewer")++ list_response = self.client.get(+ f"/api/projects/{self.team.id}/comments?scope=conversations_ticket&item_id={self.ticket.id}"+ )+ assert len(list_response.json()["results"]) == 1++ create_response = self.client.post(+ f"/api/projects/{self.team.id}/comments",+ {+ "content": "viewer trying to reply",+ "scope": "conversations_ticket",+ "item_id": str(self.ticket.id),+ "item_context": {"author_type": "support", "is_private": False},+ },+ )+ assert create_response.status_code == status.HTTP_403_FORBIDDEN++ def test_editor_can_list_and_create_ticket_message(self) -> None:+ AccessControl.objects.filter(resource_id=str(self.ticket.id)).update(access_level="editor")++ create_response = self.client.post(+ f"/api/projects/{self.team.id}/comments",+ {+ "content": "editor reply",+ "scope": "conversations_ticket",+ "item_id": str(self.ticket.id),+ "item_context": {"author_type": "support", "is_private": False},+ },+ )+ assert create_response.status_code == status.HTTP_201_CREATED++ def test_creator_downgraded_to_viewer_cannot_edit_own_ticket_message(self) -> None:+ AccessControl.objects.filter(resource_id=str(self.ticket.id)).update(access_level="editor")+ own_message = Comment.objects.create(+ team=self.team,+ created_by=self.member,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="my reply",+ )+ AccessControl.objects.filter(resource_id=str(self.ticket.id)).update(access_level="viewer")++ response = self.client.patch(+ f"/api/projects/{self.team.id}/comments/{own_message.id}?scope=conversations_ticket",+ {"content": "edited after being downgraded"},+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN+ own_message.refresh_from_db()+ assert own_message.content == "my reply"++ def test_cannot_rescope_existing_comment_into_denied_ticket(self) -> None:+ own_comment = Comment.objects.create(+ team=self.team,+ created_by=self.member,+ scope="Notebook",+ item_id="1",+ content="a notebook comment",+ )++ response = self.client.patch(+ f"/api/projects/{self.team.id}/comments/{own_comment.id}",+ {"scope": "conversations_ticket", "item_id": str(self.ticket.id)},+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN+ own_comment.refresh_from_db()+ assert own_comment.scope == "Notebook"++ def _deny_ticket_resource(self) -> None:+ AccessControl.objects.filter(resource_id=str(self.ticket.id)).delete()+ AccessControl.objects.create(+ resource="ticket",+ resource_id=None,+ organization_member=self.member.organization_memberships.get(organization=self.organization),+ team=self.team,+ access_level="none",+ )++ def test_member_denied_ticket_resource_cannot_list_messages_across_tickets(self) -> None:+ self._deny_ticket_resource()++ response = self.client.get(f"/api/projects/{self.team.id}/comments?scope=conversations_ticket")++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["results"] == []++ def test_member_denied_ticket_resource_still_lists_messages_of_specifically_granted_ticket(self) -> None:+ self._deny_ticket_resource()+ AccessControl.objects.create(+ resource="ticket",+ resource_id=str(self.ticket.id),+ organization_member=self.member.organization_memberships.get(organization=self.organization),+ team=self.team,+ access_level="viewer",+ )++ response = self.client.get(f"/api/projects/{self.team.id}/comments?scope=conversations_ticket")++ assert [result["content"] for result in response.json()["results"]] == ["a private message"]++ def test_viewer_cannot_complete_ticket_task(self) -> None:+ AccessControl.objects.filter(resource_id=str(self.ticket.id)).update(access_level="viewer")+ task = Comment.objects.create(+ team=self.team,+ created_by=self.member,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="a ticket task",+ is_task=True,+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/comments/{task.id}/complete?scope=conversations_ticket",+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN+ task.refresh_from_db()+ assert task.completed_at is None++class TestDiscussionMentionInternalEvents(APIBaseTest, QueryMatchingTest):@mock.patch("posthog.models.comment.utils.produce_internal_event")@mock.patch("posthog.tasks.email.send_discussions_mentioned.delay")diff --git a/posthog/rbac/test/test_user_access_control_pbt.py b/posthog/rbac/test/test_user_access_control_pbt.pyindex bb088d2b328b..14d59bbe77d1 100644--- a/posthog/rbac/test/test_user_access_control_pbt.py+++ b/posthog/rbac/test/test_user_access_control_pbt.py@@ -209,10 +209,23 @@ def _build_evaluation(team: Team, user: User, model_cls: type[models.Model]) ->)+def _build_ticket(team: Team, user: User, model_cls: type[models.Model]) -> models.Model:+ # ticket_number has a per-team unique constraint enforced via create_with_number's+ # SELECT FOR UPDATE + MAX() dance; the generic field-filler has no way to satisfy+ # a uniqueness constraint, so every generically-built Ticket would collide on 0.+ manager: Any = model_cls._default_manager+ return manager.create_with_number(+ team=team,+ widget_session_id=f"pbt-ticket-{next(_unique_counter)}",+ distinct_id=f"pbt-ticket-{next(_unique_counter)}",+ )++# resource -> factory for models whose validation the generic build_instance can't# satisfy. Preferred over EXCLUSIONS so the resource keeps coverage.FACTORY_OVERRIDES: dict[APIScopeObject, Callable[[Team, User, type[models.Model]], models.Model]] = {"evaluation": _build_evaluation,+ "ticket": _build_ticket,}diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.pyindex d22d1fb3738f..2372f9cc0551 100644--- a/posthog/rbac/user_access_control.py+++ b/posthog/rbac/user_access_control.py@@ -81,6 +81,7 @@ ACCESS_CONTROL_RESOURCES: tuple[APIScopeObject, ...] = ("session_recording","sharing_configuration","survey",+ "ticket","web_analytics","activity_log","error_tracking",@@ -108,6 +109,9 @@ RESOURCE_INHERITANCE_MAP: dict[APIScopeObject, APIScopeObject] = {"experiment_saved_metric": "experiment","experiment_holdout": "experiment","dashboard_template": "dashboard",+ # Saved ticket views (the `conversation` scope) share the Support product's+ # single "ticket" RBAC resource, so admins configure one control instead of two.+ "conversation": "ticket",# Marketing analytics doesn't have its own RBAC resource yet — inherit from# web_analytics so the existing per-team controls actually gate it (matches# the frontend mapping in sceneTypes.ts: Scene.MarketingAnalytics ->diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex 852489510334..aa47b204b432 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -36,6 +36,7 @@ from products.conversations.backend.models.constants import Channel, ChannelDetafrom products.conversations.backend.person_lookup import PERSON_EMAIL_LOOKUP_QUERY, _get_persons_by_emailfrom ee.clickhouse.materialized_columns.columns import get_bloom_filter_lower_index_name+from ee.models.rbac.access_control import AccessControlfrom ee.models.rbac.role import Role@@ -902,6 +903,31 @@ class TestBulkUpdateStatus(APIBaseTest):other_ticket.refresh_from_db()self.assertEqual(other_ticket.status, Status.NEW)+ def test_skips_tickets_denied_at_object_level(self, mock_on_commit):+ # Bulk status update must respect object-level access control the same way single-ticket+ # updates do via get_object() -- a ticket explicitly denied to the caller must not be+ # mutated just because its UUID was included in the request.+ self.organization.available_product_features = [{"key": "access_control", "name": "Access control"}]+ self.organization.save()+ AccessControl.objects.create(+ resource="ticket",+ resource_id=str(self.tickets[0].id),+ organization_member=self.user.organization_memberships.get(organization=self.organization),+ team=self.team,+ access_level="none",+ )+ ids = [str(t.id) for t in self.tickets]+ response = self.client.post(+ self._bulk_url(),+ {"ids": ids, "status": "open"},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["updated"], 2)+ self.assertNotIn(str(self.tickets[0].id), response.json()["ids"])+ self.tickets[0].refresh_from_db()+ self.assertEqual(self.tickets[0].status, Status.NEW)+def test_creates_activity_log_entries(self, mock_on_commit):ids = [str(t.id) for t in self.tickets[:2]]self.client.post(@@ -2434,3 +2460,177 @@ class TestAiFeedbackAPI(APIBaseTest):format="json",)assert response.status_code == status.HTTP_400_BAD_REQUEST+++class TestTicketAccessControl(APIBaseTest):+ """Resource- and object-level access control for support tickets (the `ticket` RBAC resource)."""++ def setUp(self) -> None:+ super().setUp()+ self.organization.available_product_features = [{"key": "access_control", "name": "Access control"}]+ self.organization.save()+ self.team.conversations_enabled = True+ self.team.save()+ # A plain member (org admins bypass access control), logged in for every request below.+ self.member = User.objects.create_and_join(self.organization, "[email protected]", "password")+ self.client.force_login(self.member)+ self.ticket = Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.WIDGET,+ widget_session_id="ac-session",+ distinct_id="user-ac",+ status=Status.OPEN,+ )++ def _set_resource_level(self, access_level: str) -> None:+ AccessControl.objects.create(resource="ticket", team=self.team, access_level=access_level)++ def _grant_object_level(self, ticket: Ticket, access_level: str) -> None:+ AccessControl.objects.create(+ resource="ticket",+ resource_id=str(ticket.id),+ organization_member=self.member.organization_memberships.get(organization=self.organization),+ team=self.team,+ access_level=access_level,+ )++ @parameterized.expand([("none", status.HTTP_403_FORBIDDEN), ("viewer", status.HTTP_200_OK)])+ def test_list_access_by_resource_level(self, access_level: str, expected_status: int) -> None:+ self._set_resource_level(access_level)+ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/")+ self.assertEqual(response.status_code, expected_status)++ @parameterized.expand([("viewer", status.HTTP_403_FORBIDDEN), ("editor", status.HTTP_200_OK)])+ def test_update_access_by_resource_level(self, access_level: str, expected_status: int) -> None:+ self._set_resource_level(access_level)+ response = self.client.patch(+ f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/",+ {"status": "resolved"},+ )+ self.assertEqual(response.status_code, expected_status, response.json())++ @parameterized.expand([("viewer", status.HTTP_403_FORBIDDEN), ("editor", status.HTTP_201_CREATED)])+ def test_reply_action_gated_by_resource_level(self, access_level: str, expected_status: int) -> None:+ # `reply` is a write @action; a viewer must not be able to post a reply.+ self._set_resource_level(access_level)+ response = self.client.post(+ f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/reply/",+ {"message": "A reply"},+ format="json",+ )+ self.assertEqual(response.status_code, expected_status, response.json())++ def test_user_access_level_reflects_resource_level(self) -> None:+ self._set_resource_level("viewer")+ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["user_access_level"], "viewer")++ def test_user_access_level_reflects_object_level(self) -> None:+ # An object-level grant for this ticket wins over the lower resource-level floor.+ self._set_resource_level("viewer")+ self._grant_object_level(self.ticket, "editor")+ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["user_access_level"], "editor")++ def test_list_hides_tickets_blocked_at_object_level(self) -> None:+ # Resource-level viewer, but one ticket is explicitly denied to the member.+ blocked = Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.WIDGET,+ widget_session_id="ac-blocked",+ distinct_id="user-ac-2",+ status=Status.OPEN,+ )+ self._set_resource_level("viewer")+ self._grant_object_level(blocked, "none")+ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ returned_ids = {r["id"] for r in response.json()["results"]}+ self.assertIn(str(self.ticket.id), returned_ids)+ self.assertNotIn(str(blocked.id), returned_ids)++ def test_retrieve_blocked_at_object_level(self) -> None:+ # Resource-level viewer would normally allow retrieve, but an explicit per-ticket+ # deny must still block the detail route (not just list filtering).+ self._set_resource_level("viewer")+ self._grant_object_level(self.ticket, "none")+ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/")+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_reply_blocked_at_object_level(self) -> None:+ # Resource-level editor would normally allow reply, but an explicit per-ticket deny+ # must still block the write action.+ self._set_resource_level("editor")+ self._grant_object_level(self.ticket, "none")+ response = self.client.post(+ f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/reply/",+ {"message": "A reply"},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_viewer_does_not_clear_unread_state_on_retrieve(self) -> None:+ # Retrieve is a read action, but it also marks the ticket read for the team - a viewer+ # must not be able to clear that shared state just by opening the ticket.+ self.ticket.unread_team_count = 3+ self.ticket.save(update_fields=["unread_team_count"])+ self._set_resource_level("viewer")++ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.ticket.refresh_from_db()+ self.assertEqual(self.ticket.unread_team_count, 3)++ def test_editor_clears_unread_state_on_retrieve(self) -> None:+ self.ticket.unread_team_count = 3+ self.ticket.save(update_fields=["unread_team_count"])+ self._set_resource_level("editor")++ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.ticket.refresh_from_db()+ self.assertEqual(self.ticket.unread_team_count, 0)++ def test_unread_count_excludes_tickets_blocked_at_object_level(self) -> None:+ # A member restricted to specific tickets must not see unread counts for tickets+ # outside their object-level access, even via the team-wide aggregate endpoint.+ blocked = Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.WIDGET,+ widget_session_id="ac-unread-blocked",+ distinct_id="user-ac-unread",+ status=Status.OPEN,+ unread_team_count=5,+ )+ self.ticket.unread_team_count = 2+ self.ticket.save(update_fields=["unread_team_count"])+ self._set_resource_level("viewer")+ self._grant_object_level(blocked, "none")++ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/unread_count/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 2)++ def test_object_access_controls_endpoint_exists(self) -> None:+ # The per-ticket access_controls route (side-panel object permissions) is wired by the mixin.+ self._set_resource_level("viewer")+ response = self.client.get(+ f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/access_controls"+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ @parameterized.expand([("viewer", status.HTTP_403_FORBIDDEN), ("editor", status.HTTP_201_CREATED)])+ def test_saved_view_create_inherits_ticket_access(self, access_level: str, expected_status: int) -> None:+ # Saved views use the `conversation` scope, which inherits the `ticket` resource's access level.+ self._set_resource_level(access_level)+ response = self.client.post(+ f"/api/projects/{self.team.id}/conversations/views/",+ {"name": "My view", "filters": {"status": ["open"]}},+ format="json",+ )+ self.assertEqual(response.status_code, expected_status, response.json())diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex 1e7d985c44f4..c35bb91a0afa 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -42,6 +42,8 @@ from posthog.models.person.util import get_person_by_distinct_id, get_persons_byfrom posthog.permissions import APIScopePermissionfrom posthog.personhog_client.caller_tag import personhog_caller_tagfrom posthog.rate_limit import ComposeTicketBurstThrottle, ComposeTicketSustainedThrottle+from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin+from posthog.rbac.user_access_control import UserAccessControlSerializerMixinfrom posthog.utils import relative_date_parsefrom products.conversations.backend.api.serializers import TicketAssignmentSerializer@@ -234,7 +236,7 @@ class TicketPersonSerializer(serializers.Serializer):return get_person_name(team, person)-class TicketSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):+class TicketSerializer(UserAccessControlSerializerMixin, TaggedItemSerializerMixin, serializers.ModelSerializer):assignee = TicketAssignmentSerializer(source="assignment", read_only=True)person = TicketPersonSerializer(read_only=True, allow_null=True)email_to = serializers.SerializerMethodField()@@ -280,6 +282,7 @@ class TicketSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):"organization_id_source","person","tags",+ "user_access_level",]read_only_fields = ["id",@@ -359,7 +362,7 @@ TICKET_ID_PARAM = OpenApiParameter(partial_update=extend_schema(parameters=[TICKET_ID_PARAM]),destroy=extend_schema(parameters=[TICKET_ID_PARAM]),)-class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.ModelViewSet):+class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):scope_object = "ticket"scope_object_read_actions = ["list", "retrieve", "unread_count", "messages"]# "create" stays listed so a ticket:write token reaches the create() override below and@@ -592,6 +595,9 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Modif order_by not in allowed_orderings:order_by = "-updated_at"+ # Hide tickets the user has been explicitly denied object-level access to (list action only).+ queryset = self._filter_queryset_by_access_level(queryset)+field_name = order_by.lstrip("-")primary: OrderBy | strif field_name in ("sla_due_at", "snoozed_until"):@@ -854,7 +860,10 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Moddef retrieve(self, request, *args, **kwargs):"""Get single ticket and mark as read by team."""instance = self.get_object()- if instance.unread_team_count > 0:+ # Marking as read is a write to shared team state - gate it by editor access so a+ # viewer can't clear the team's unread indicator just by opening a ticket.+ can_edit = self.user_access_control.check_access_level_for_object(instance, required_level="editor")+ if can_edit and instance.unread_team_count > 0:instance.unread_team_count = 0instance.save(update_fields=["unread_team_count"])# Invalidate cache since unread count changed@@ -1078,7 +1087,10 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Mod"""Update the status of multiple tickets in a single request.Only tickets belonging to the current team are affected; other-team UUIDs- are silently ignored. Tickets already in the requested status are skipped.+ are silently ignored. Tickets the caller lacks editor-level access to (denied+ or view-only via object-level access control) are silently skipped too, the+ same way single-ticket updates enforce object-level access via get_object().+ Tickets already in the requested status are skipped."""serializer = BulkUpdateStatusRequestSerializer(data=request.data)serializer.is_valid(raise_exception=True)@@ -1088,6 +1100,12 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Modchanged: list[tuple[Ticket, str]] = []with transaction.atomic():tickets = list(self.get_queryset().filter(id__in=ticket_ids).select_for_update(of=("self",)))+ self.user_access_control.preload_object_access_controls(tickets)+ tickets = [+ ticket+ for ticket in tickets+ if self.user_access_control.check_access_level_for_object(ticket, required_level="editor")+ ]for ticket in tickets:old_status = ticket.statusif old_status == new_status:@@ -1124,8 +1142,11 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Mod"""Get total unread ticket count for the team.- Returns the sum of unread_team_count for all non-resolved tickets.- Cached in Redis for 30 seconds, invalidated on changes.+ Returns the sum of unread_team_count for all non-resolved tickets visible to the+ caller. The team-wide Redis cache (30s TTL, invalidated on changes) is only used for+ callers without object-level ticket restrictions, since it holds one unscoped total+ per team - serving it to a restricted member would leak counts for tickets they can't+ see."""team_id = self.team_id@@ -1133,22 +1154,23 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Modif not self.team.conversations_enabled:return Response({"count": 0})- # Try cache first- cached_count = get_cached_unread_count(team_id)- if cached_count is not None:- return Response({"count": cached_count})+ uac = self.user_access_control+ is_restricted = bool(uac.blocked_resource_ids_by_scope.get("ticket")) or not uac.has_resource_access("ticket")++ if not is_restricted:+ cached_count = get_cached_unread_count(team_id)+ if cached_count is not None:+ return Response({"count": cached_count})# Query database - only non-resolved tickets with unread messages- result = (- Ticket.objects.filter(team_id=team_id)- .exclude(status="resolved")- .filter(unread_team_count__gt=0)- .aggregate(total=Sum("unread_team_count"))- )- count = result["total"] or 0+ queryset = Ticket.objects.filter(team_id=team_id).exclude(status="resolved").filter(unread_team_count__gt=0)+ if is_restricted:+ queryset = uac.filter_queryset_by_access_level(queryset)++ count = queryset.aggregate(total=Sum("unread_team_count"))["total"] or 0- # Cache the result- set_cached_unread_count(team_id, count)+ if not is_restricted:+ set_cached_unread_count(team_id, count)return Response({"count": count})diff --git a/products/conversations/frontend/components/Assignee/AssigneeSelect.tsx b/products/conversations/frontend/components/Assignee/AssigneeSelect.tsxindex 17834fe21ca1..455660b773d3 100644--- a/products/conversations/frontend/components/Assignee/AssigneeSelect.tsx+++ b/products/conversations/frontend/components/Assignee/AssigneeSelect.tsx@@ -12,10 +12,12 @@ export const AssigneeSelect = ({assignee,onChange,children,+ disabledReason,}: {assignee: TicketAssigneeonChange: (assignee: TicketAssignee) => voidchildren: (assignee: Assignee, isOpen: boolean) => JSX.Element+ disabledReason?: string}): JSX.Element => {const { setSearch, ensureAssigneeTypesLoaded } = useActions(assigneeSelectLogic)const [showPopover, setShowPopover] = useState(false)@@ -30,6 +32,16 @@ export const AssigneeSelect = ({ensureAssigneeTypesLoaded()}, [ensureAssigneeTypesLoaded])+ if (disabledReason) {+ return (+ <div>+ <AssigneeResolver assignee={assignee}>+ {({ assignee: resolvedAssignee }) => children(resolvedAssignee, false)}+ </AssigneeResolver>+ </div>+ )+ }+return (<LemonDropdowncloseOnClickInside={false}diff --git a/products/conversations/frontend/components/Chat/ChatView.tsx b/products/conversations/frontend/components/Chat/ChatView.tsxindex 84a892ffe6b3..52c1b2f4174a 100644--- a/products/conversations/frontend/components/Chat/ChatView.tsx+++ b/products/conversations/frontend/components/Chat/ChatView.tsx@@ -46,6 +46,8 @@ export interface ChatViewProps {threadExtras?: TimelineExtra[]/** Blocks sending customer-facing messages (private notes stay available) */replyDisabledReason?: string | JSX.Element+ /** Blocks sending entirely, including private notes (e.g. the user lacks edit access) */+ sendDisabledReason?: string | JSX.Element/** Whether draft mode is on: tints the composer green and confirms the recipient before sending */draftMode?: boolean/** Called when the draft-mode toggle changes */@@ -59,6 +61,7 @@ export interface ChatViewProps {latestAiMessageId?: string | nullfeedbackByMessageId?: Record<string, AiReplyFeedbackRating>showAiReplyFeedback?: boolean+ aiReplyFeedbackDisabledReason?: stringonSubmitAiReplyFeedback?: (messageId: string, rating: AiReplyFeedbackRating, feedbackText?: string) => void}@@ -84,6 +87,7 @@ export function ChatView({onPrivateChange,extraActions,replyDisabledReason,+ sendDisabledReason,draftMode,onDraftModeChange,sendConfirmationMessage,@@ -92,6 +96,7 @@ export function ChatView({latestAiMessageId,feedbackByMessageId,showAiReplyFeedback,+ aiReplyFeedbackDisabledReason,onSubmitAiReplyFeedback,}: ChatViewProps): JSX.Element {const listMinHeight = minHeight ?? '400px'@@ -114,6 +119,7 @@ export function ChatView({latestAiMessageId={latestAiMessageId}feedbackByMessageId={feedbackByMessageId}showAiReplyFeedback={showAiReplyFeedback}+ aiReplyFeedbackDisabledReason={aiReplyFeedbackDisabledReason}onSubmitAiReplyFeedback={onSubmitAiReplyFeedback}extras={threadExtras}/>@@ -129,6 +135,7 @@ export function ChatView({onPrivateChange={onPrivateChange}extraActions={extraActions}replyDisabledReason={replyDisabledReason}+ sendDisabledReason={sendDisabledReason}draftMode={draftMode}onDraftModeChange={onDraftModeChange}sendConfirmationMessage={sendConfirmationMessage}diff --git a/products/conversations/frontend/components/Chat/Message.tsx b/products/conversations/frontend/components/Chat/Message.tsxindex 2d01cafb30d4..1b0f60e5f561 100644--- a/products/conversations/frontend/components/Chat/Message.tsx+++ b/products/conversations/frontend/components/Chat/Message.tsx@@ -24,6 +24,7 @@ export interface MessageProps {deliveryStatus?: MessageDeliveryStatusshowAiReplyFeedback?: booleanaiReplyFeedbackRating?: AiReplyFeedbackRating | null+ aiReplyFeedbackDisabledReason?: stringonSubmitAiReplyFeedback?: (rating: AiReplyFeedbackRating, feedbackText?: string) => void}@@ -33,6 +34,7 @@ export function Message({deliveryStatus,showAiReplyFeedback = false,aiReplyFeedbackRating = null,+ aiReplyFeedbackDisabledReason,onSubmitAiReplyFeedback,}: MessageProps): JSX.Element {const profileType = message.authorType === 'AI' ? 'bot' : 'person'@@ -48,14 +50,14 @@ export function Message({!!onSubmitAiReplyFeedbackfunction submitRating(rating: AiReplyFeedbackRating): void {- if (aiReplyFeedbackRating || !onSubmitAiReplyFeedback) {+ if (aiReplyFeedbackDisabledReason || aiReplyFeedbackRating || !onSubmitAiReplyFeedback) {return}onSubmitAiReplyFeedback(rating)}function submitBadFeedbackText(): void {- if (!feedbackText.trim() || !onSubmitAiReplyFeedback) {+ if (aiReplyFeedbackDisabledReason || !feedbackText.trim() || !onSubmitAiReplyFeedback) {return}onSubmitAiReplyFeedback('bad', feedbackText.trim())@@ -135,7 +137,8 @@ export function Message({size="xsmall"tooltip="Good reply"disabledReason={- aiReplyFeedbackRating ? 'Feedback already recorded' : undefined+ aiReplyFeedbackDisabledReason ??+ (aiReplyFeedbackRating ? 'Feedback already recorded' : undefined)}onClick={() => submitRating('good')}data-attr="ai-reply-feedback-good"@@ -154,7 +157,8 @@ export function Message({size="xsmall"tooltip="Bad reply"disabledReason={- aiReplyFeedbackRating ? 'Feedback already recorded' : undefined+ aiReplyFeedbackDisabledReason ??+ (aiReplyFeedbackRating ? 'Feedback already recorded' : undefined)}onClick={() => submitRating('bad')}data-attr="ai-reply-feedback-bad"@@ -170,6 +174,7 @@ export function Message({value={feedbackText}onChange={setFeedbackText}onPressEnter={submitBadFeedbackText}+ disabledReason={aiReplyFeedbackDisabledReason}autoFocus/><LemonButton@@ -177,7 +182,8 @@ export function Message({size="small"onClick={submitBadFeedbackText}disabledReason={- !feedbackText.trim() ? 'Please type a few words' : undefined+ aiReplyFeedbackDisabledReason ??+ (!feedbackText.trim() ? 'Please type a few words' : undefined)}>Submitdiff --git a/products/conversations/frontend/components/Chat/MessageInput.test.tsx b/products/conversations/frontend/components/Chat/MessageInput.test.tsxindex 2d653bb40e08..c0d0ddb7ba44 100644--- a/products/conversations/frontend/components/Chat/MessageInput.test.tsx+++ b/products/conversations/frontend/components/Chat/MessageInput.test.tsx@@ -14,12 +14,24 @@ import { MessageInput } from './MessageInput'jest.mock('../Editor', () => {const React = jest.requireActual<typeof import('react')>('react')return {- SupportEditor: ({ onCreate }: { onCreate: (editor: unknown) => void }) => {+ SupportEditor: ({+ onCreate,+ onPressCmdEnter,+ disabled,+ }: {+ onCreate: (editor: unknown) => void+ onPressCmdEnter: () => void+ disabled?: boolean+ }) => {React.useEffect(() => {onCreate({ getJSON: () => ({ type: 'doc' }), clear: () => {} })// eslint-disable-next-line react-hooks/exhaustive-deps}, [])- return React.createElement('div')+ return React.createElement(+ 'button',+ { 'data-attr': 'support-editor', 'data-disabled': disabled, onClick: onPressCmdEnter },+ 'Editor shortcut'+ )},serializeToMarkdown: (): string => 'hello',}@@ -31,7 +43,7 @@ const SEND_AND_SET_STATUS_OPTIONS: { value: TicketStatus; statusLabel: string }[{ value: 'resolved', statusLabel: 'resolved' },]-describe('MessageInput send-and-set-status dropdown', () => {+describe('MessageInput', () => {beforeEach(() => {initKeaTests()})@@ -40,6 +52,26 @@ describe('MessageInput send-and-set-status dropdown', () => {cleanup()})+ it('disables the editor and blocks its keyboard submit shortcut without edit access', async () => {+ const onSendMessage = jest.fn()++ render(+ <Provider>+ <MessageInput+ onSendMessage={onSendMessage}+ messageSending={false}+ draftContent={{ type: 'doc', content: [] }}+ sendDisabledReason="Requires edit access"+ />+ </Provider>+ )++ const editor = screen.getByTestId('support-editor')+ expect(editor).toHaveAttribute('data-disabled', 'true')+ await userEvent.click(editor)+ expect(onSendMessage).not.toHaveBeenCalled()+ })+// Guards the private-note flag through the dropdown path: dropping it would deliver an// internal note to the customer as a real reply.test.each<[string, boolean, string]>([diff --git a/products/conversations/frontend/components/Chat/MessageInput.tsx b/products/conversations/frontend/components/Chat/MessageInput.tsxindex 82f97df1e5c3..004a25a27d41 100644--- a/products/conversations/frontend/components/Chat/MessageInput.tsx+++ b/products/conversations/frontend/components/Chat/MessageInput.tsx@@ -39,6 +39,8 @@ export interface MessageInputProps {extraActions?: React.ReactNode/** Blocks sending customer-facing messages (private notes stay available). Shown as the button's disabled tooltip. */replyDisabledReason?: string | JSX.Element+ /** Blocks sending entirely, including private notes (e.g. the user lacks edit access). Takes precedence. */+ sendDisabledReason?: string | JSX.Element/** Whether draft mode is on: tints the composer green and confirms the recipient before sending */draftMode?: boolean/** Called when the draft-mode toggle changes; when provided, the toggle renders left of the send button */@@ -65,6 +67,7 @@ export function MessageInput({onPrivateChange,extraActions,replyDisabledReason,+ sendDisabledReason,draftMode = false,onDraftModeChange,sendConfirmationMessage,@@ -89,8 +92,8 @@ export function MessageInput({const sendVerb = isPrivate ? 'Attach' : 'Send'const handleSubmit = (statusAfterSend?: TicketStatus): void => {- // These guard the Cmd+Enter path, which bypasses the (disabled) button.- if (replyDisabledReason && !isPrivate) {+ // These guard the Cmd+Enter path, which bypasses the disabled button.+ if (sendDisabledReason || (replyDisabledReason && !isPrivate)) {return}if (messageSending || isUploading) {@@ -160,14 +163,21 @@ export function MessageInput({}}- const sendBlockedReason =- replyDisabledReason && !isPrivate- ? replyDisabledReason- : isEmpty- ? 'No message'- : isUploading- ? 'Uploading image...'- : undefined+ const sendBlockedReason = sendDisabledReason+ ? sendDisabledReason+ : replyDisabledReason && !isPrivate+ ? replyDisabledReason+ : isEmpty+ ? 'No message'+ : isUploading+ ? 'Uploading image...'+ : undefined+ const sendControlDisabledReason =+ typeof sendDisabledReason === 'string'+ ? sendDisabledReason+ : sendDisabledReason+ ? 'Sending is disabled'+ : undefinedreturn (<div>@@ -183,7 +193,7 @@ export function MessageInput({onUpdate={handleUpdate}onPressCmdEnter={() => handleSubmit()}onUploadingChange={setIsUploading}- disabled={messageSending}+ disabled={messageSending || !!sendDisabledReason}minRows={minRows}className={isPrivate@@ -200,6 +210,7 @@ export function MessageInput({<LemonCheckboxchecked={isPrivate}onChange={setIsPrivate}+ disabledReason={sendControlDisabledReason}label={<span className="inline-flex items-center gap-1"><IconLock className="text-sm" />@@ -222,7 +233,10 @@ export function MessageInput({checked={draftMode}onChange={onDraftModeChange}label="Draft mode"- disabledReason={isPrivate ? 'Draft mode has no effect on private notes' : undefined}+ disabledReason={+ sendControlDisabledReason ??+ (isPrivate ? 'Draft mode has no effect on private notes' : undefined)+ }/></span></Tooltip>diff --git a/products/conversations/frontend/components/Chat/MessageList.tsx b/products/conversations/frontend/components/Chat/MessageList.tsxindex 4c54b5bad1c2..5351dfa127b5 100644--- a/products/conversations/frontend/components/Chat/MessageList.tsx+++ b/products/conversations/frontend/components/Chat/MessageList.tsx@@ -27,6 +27,7 @@ export interface MessageListProps {feedbackByMessageId?: Record<string, AiReplyFeedbackRating>/** Whether AI reply feedback controls are enabled */showAiReplyFeedback?: boolean+ aiReplyFeedbackDisabledReason?: stringonSubmitAiReplyFeedback?: (messageId: string, rating: AiReplyFeedbackRating, feedbackText?: string) => void/** Non-message timeline entries, placed among the messages by their own timestamp. Opt-in, so a* customer-facing view never receives team-only content. */@@ -56,6 +57,7 @@ export function MessageList({latestAiMessageId = null,feedbackByMessageId = {},showAiReplyFeedback = false,+ aiReplyFeedbackDisabledReason,onSubmitAiReplyFeedback,extras = [],}: MessageListProps): JSX.Element {@@ -134,6 +136,7 @@ export function MessageList({showAiReplyFeedback && message.id === latestAiMessageId && message.authorType === 'AI'}aiReplyFeedbackRating={feedbackByMessageId[message.id] ?? null}+ aiReplyFeedbackDisabledReason={aiReplyFeedbackDisabledReason}onSubmitAiReplyFeedback={onSubmitAiReplyFeedback? (rating, feedbackText) => onSubmitAiReplyFeedback(message.id, rating, feedbackText)diff --git a/products/conversations/frontend/components/ComposeTicket/ComposeTicketButton.tsx b/products/conversations/frontend/components/ComposeTicket/ComposeTicketButton.tsxindex dcd808490b77..f00f53a232f7 100644--- a/products/conversations/frontend/components/ComposeTicket/ComposeTicketButton.tsx+++ b/products/conversations/frontend/components/ComposeTicket/ComposeTicketButton.tsx@@ -5,12 +5,15 @@ import { useState } from 'react'import { IconLetter } from '@posthog/icons'import { LemonButton, LemonButtonProps } from '@posthog/lemon-ui'+import { AccessControlAction } from 'lib/components/AccessControlAction'import { FEATURE_FLAGS } from 'lib/constants'import { Popover } from 'lib/lemon-ui/Popover'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { AccessControlLevel, AccessControlResourceType } from '~/types'+import { composeTicketLogic } from './composeTicketLogic'interface ComposeTicketButtonProps {@@ -66,23 +69,28 @@ export function ComposeTicketButton({</div>}>- <LemonButton- type={type}- size={size}- icon={<IconLetter />}- tooltip={iconOnly ? 'New ticket' : undefined}- onClick={() => {- if (conversationsEnabled) {- openComposeModal({ distinctId, email })- onCompose?.()- } else {- setShowDisabledPopover(true)- }- }}- data-attr="compose-ticket-button"+ <AccessControlAction+ resourceType={AccessControlResourceType.Ticket}+ minAccessLevel={AccessControlLevel.Editor}>- {iconOnly ? null : 'New ticket'}- </LemonButton>+ <LemonButton+ type={type}+ size={size}+ icon={<IconLetter />}+ tooltip={iconOnly ? 'New ticket' : undefined}+ onClick={() => {+ if (conversationsEnabled) {+ openComposeModal({ distinctId, email })+ onCompose?.()+ } else {+ setShowDisabledPopover(true)+ }+ }}+ data-attr="compose-ticket-button"+ >+ {iconOnly ? null : 'New ticket'}+ </LemonButton>+ </AccessControlAction></Popover></>)diff --git a/products/conversations/frontend/components/SavedViews/SavedViewsModal.tsx b/products/conversations/frontend/components/SavedViews/SavedViewsModal.tsxindex 148636fcbfd6..b7bbf1be2daa 100644--- a/products/conversations/frontend/components/SavedViews/SavedViewsModal.tsx+++ b/products/conversations/frontend/components/SavedViews/SavedViewsModal.tsx@@ -8,6 +8,9 @@ import { TZLabel } from 'lib/components/TZLabel'import { More } from 'lib/lemon-ui/LemonButton/More'import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'++import { AccessControlLevel, AccessControlResourceType } from '~/types'import { type SavedTicketView, type TicketViewFilters, normalizeAssigneeFilter } from '../../types'import { AssigneeLabelDisplay, AssigneeResolver } from '../Assignee'@@ -80,6 +83,8 @@ function FiltersSummary({ filters }: { filters: TicketViewFilters }): JSX.Elemenfunction SaveViewModal({ id }: TicketViewsLogicProps): JSX.Element {const { isSaveModalOpen, viewName, currentFilters } = useValues(ticketViewsLogic({ id }))const { closeSaveModal, setViewName, saveView } = useActions(ticketViewsLogic({ id }))+ const editDisabledReason =+ getAccessControlDisabledReason(AccessControlResourceType.Ticket, AccessControlLevel.Editor) ?? undefinedreturn (<LemonModal@@ -94,7 +99,7 @@ function SaveViewModal({ id }: TicketViewsLogicProps): JSX.Element {<LemonButtontype="primary"onClick={saveView}- disabledReason={!viewName.trim() ? 'Enter a name' : undefined}+ disabledReason={editDisabledReason ?? (!viewName.trim() ? 'Enter a name' : undefined)}>Save view</LemonButton>@@ -107,7 +112,8 @@ function SaveViewModal({ id }: TicketViewsLogicProps): JSX.Element {value={viewName}onChange={setViewName}autoFocus- onPressEnter={saveView}+ disabledReason={editDisabledReason}+ onPressEnter={editDisabledReason ? undefined : saveView}/><FiltersSummary filters={currentFilters} /></div>@@ -122,6 +128,8 @@ export function SavedViewsModal({ id }: TicketViewsLogicProps): JSX.Element {const { closeModal, openSaveModal, deleteView, loadView, updateView, toggleFavorite, setSearchTerm } = useActions(ticketViewsLogic({ id }))+ const editDisabledReason =+ getAccessControlDisabledReason(AccessControlResourceType.Ticket, AccessControlLevel.Editor) ?? undefinedconst columns: LemonTableColumns<SavedTicketView> = [{@@ -133,6 +141,7 @@ export function SavedViewsModal({ id }: TicketViewsLogicProps): JSX.Element {size="xsmall"loading={favoritingShortIds.includes(view.short_id)}onClick={() => toggleFavorite(view)}+ disabledReason={editDisabledReason}icon={view.is_favorited ? (<IconHeartFilled className="text-danger" />@@ -179,6 +188,7 @@ export function SavedViewsModal({ id }: TicketViewsLogicProps): JSX.Element {Load</LemonButton><More+ disabledReason={editDisabledReason}overlay={<LemonMenuOverlayitems={[@@ -268,7 +278,7 @@ export function SavedViewsModal({ id }: TicketViewsLogicProps): JSX.Element {width={720}footer={<div className="flex justify-between w-full">- <LemonButton type="primary" onClick={openSaveModal}>+ <LemonButton type="primary" onClick={openSaveModal} disabledReason={editDisabledReason}>Save current view</LemonButton><LemonButton type="secondary" onClick={closeModal}>diff --git a/products/conversations/frontend/components/TicketTags/index.tsx b/products/conversations/frontend/components/TicketTags/index.tsxindex 6d5e08cfd7c1..5857b15da7a6 100644--- a/products/conversations/frontend/components/TicketTags/index.tsx+++ b/products/conversations/frontend/components/TicketTags/index.tsx@@ -1,5 +1,7 @@import { useValues } from 'kea'+import { Tooltip } from '@posthog/lemon-ui'+import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'import { tagsModel } from '~/models/tagsModel'@@ -9,6 +11,7 @@ export interface TicketTagsProps {onChange: (tags: string[]) => voidsaving?: booleanclassName?: string+ disabledReason?: string}export function TicketTags({@@ -16,18 +19,31 @@ export function TicketTags({onChange,saving = false,className = 'justify-end p-2',+ disabledReason,}: TicketTagsProps): JSX.Element {const { tags: tagsAvailable, tagsLoading } = useValues(tagsModel)- return (+ const tagsDisplay = (<ObjectTagstags={tags}- onChange={onChange}- saving={saving || tagsLoading}- tagsAvailable={tagsAvailable}+ {...(disabledReason+ ? { staticOnly: true as const }+ : {+ onChange,+ saving: saving || tagsLoading,+ tagsAvailable,+ })}className={className}data-attr="ticket-tags"actionButtonSize="medium"/>)++ return disabledReason ? (+ <Tooltip title={disabledReason}>+ <span>{tagsDisplay}</span>+ </Tooltip>+ ) : (+ tagsDisplay+ )}diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex 5f48f69fc061..0243938fd674 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -682,7 +682,7 @@ export interface TicketPersonApi {}/**- * Serializer mixin that handles tags for objects.+ * Mixin for serializers to add user access control fields*/export interface TicketApi {readonly id: string@@ -768,6 +768,11 @@ export interface TicketApi {readonly organization_id_source: string | nullreadonly person: TicketPersonApi | nulltags?: unknown[]+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level: string | null}export interface PaginatedTicketListApi {@@ -780,7 +785,7 @@ export interface PaginatedTicketListApi {}/**- * Serializer mixin that handles tags for objects.+ * Mixin for serializers to add user access control fields*/export interface PatchedTicketApi {readonly id?: string@@ -866,6 +871,11 @@ export interface PatchedTicketApi {readonly organization_id_source?: string | nullreadonly person?: TicketPersonApi | nulltags?: unknown[]+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level?: string | null}/**diff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.tsindex 54239c01bc16..07a022a64b98 100644--- a/products/conversations/frontend/generated/api.ts+++ b/products/conversations/frontend/generated/api.ts@@ -482,7 +482,10 @@ export const getConversationsTicketsBulkUpdateStatusCreateUrl = (projectId: stri* Update the status of multiple tickets in a single request.** Only tickets belonging to the current team are affected; other-team UUIDs- * are silently ignored. Tickets already in the requested status are skipped.+ * are silently ignored. Tickets the caller lacks editor-level access to (denied+ * or view-only via object-level access control) are silently skipped too, the+ * same way single-ticket updates enforce object-level access via get_object().+ * Tickets already in the requested status are skipped.*/export const conversationsTicketsBulkUpdateStatusCreate = async (projectId: string,@@ -560,8 +563,11 @@ export const getConversationsTicketsUnreadCountRetrieveUrl = (projectId: string)/*** Get total unread ticket count for the team.*- * Returns the sum of unread_team_count for all non-resolved tickets.- * Cached in Redis for 30 seconds, invalidated on changes.+ * Returns the sum of unread_team_count for all non-resolved tickets visible to the+ * caller. The team-wide Redis cache (30s TTL, invalidated on changes) is only used for+ * callers without object-level ticket restrictions, since it holds one unscoped total+ * per team - serving it to a restricted member would leak counts for tickets they can't+ * see.*/export const conversationsTicketsUnreadCountRetrieve = async (projectId: string,diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.tsindex 85adfbbce936..9d4f40b0a7e3 100644--- a/products/conversations/frontend/generated/api.zod.ts+++ b/products/conversations/frontend/generated/api.zod.ts@@ -190,7 +190,7 @@ export const ConversationsTicketsUpdateBody = /* @__PURE__ */ zodsnoozed_until: zod.iso.datetime({ offset: true }).nullish(),tags: zod.array(zod.unknown()).optional(),})- .describe('Serializer mixin that handles tags for objects.')+ .describe('Mixin for serializers to add user access control fields')export const ConversationsTicketsPartialUpdateBody = /* @__PURE__ */ zod.object({@@ -225,7 +225,7 @@ export const ConversationsTicketsPartialUpdateBody = /* @__PURE__ */ zodsnoozed_until: zod.iso.datetime({ offset: true }).nullish(),tags: zod.array(zod.unknown()).optional(),})- .describe('Serializer mixin that handles tags for objects.')+ .describe('Mixin for serializers to add user access control fields')/*** Record reviewer feedback on an AI reply, captured to the internal analytics project.@@ -280,7 +280,10 @@ export const ConversationsTicketsReplyCreateBody = /* @__PURE__ */ zod* Update the status of multiple tickets in a single request.** Only tickets belonging to the current team are affected; other-team UUIDs- * are silently ignored. Tickets already in the requested status are skipped.+ * are silently ignored. Tickets the caller lacks editor-level access to (denied+ * or view-only via object-level access control) are silently skipped too, the+ * same way single-ticket updates enforce object-level access via get_object().+ * Tickets already in the requested status are skipped.*/export const conversationsTicketsBulkUpdateStatusCreateBodyIdsMax = 500diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.test.ts b/products/conversations/frontend/scenes/ticket/SupportTicketScene.test.tsnew file mode 100644index 000000000000..dc6c197f728a--- /dev/null+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.test.ts@@ -0,0 +1,19 @@+import { scene } from './SupportTicketScene'++describe('SupportTicketScene paramsToProps', () => {+ // supportTicketSceneLogic is keyed via `key((props) => props.id)`. App.tsx binds the scene's+ // logic (and the side panel context selector reads it) using whatever `paramsToProps` returns,+ // while the rendered component separately builds `supportTicketSceneLogic({ id: ticketId })`.+ // If `paramsToProps` ever stops returning `id` matching that same value, those become two+ // different logic instances: the bound one stays empty, and the ticket detail side panel's+ // access control tab silently disappears (the reported regression this test guards).+ it('keys paramsToProps by id, matching the value the component builds its logic with', () => {+ const props = scene.paramsToProps?.({ params: { ticketId: 'ticket-123' }, searchParams: {}, hashParams: {} })+ expect(props).toEqual(expect.objectContaining({ id: 'ticket-123' }))+ })++ it('falls back to the "new" ticket key when no ticketId param is present', () => {+ const props = scene.paramsToProps?.({ params: {}, searchParams: {}, hashParams: {} })+ expect(props).toEqual(expect.objectContaining({ id: 'new' }))+ })+})diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsxindex 98ed5803ce30..17585beb0db3 100644--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx@@ -5,11 +5,13 @@ import { useRef } from 'react'import { IconChevronDown } from '@posthog/icons'import { LemonButton, LemonCard, LemonSelect, LemonTag, Link, Spinner } from '@posthog/lemon-ui'+import { AccessControlAction } from 'lib/components/AccessControlAction'import { Resizer } from 'lib/components/Resizer/Resizer'import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'import { TZLabel } from 'lib/components/TZLabel'import { dayjs } from 'lib/dayjs'import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { newInternalTab } from 'lib/utils/newInternalTab'import { PersonDisplay } from 'scenes/persons/PersonDisplay'import { SceneExport } from 'scenes/sceneTypes'@@ -20,7 +22,7 @@ import { userLogic } from 'scenes/userLogic'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'-import { Breadcrumb } from '~/types'+import { AccessControlLevel, AccessControlResourceType, Breadcrumb } from '~/types'import { AssigneeIconDisplay, AssigneeLabelDisplay, AssigneeSelect } from '../../components/Assignee'import { ChannelsTag, getChannelThreadUrl } from '../../components/Channels/ChannelsTag'@@ -56,7 +58,11 @@ export const scene: SceneExport<{ ticketId: string; id: string }> = {component: SupportTicketScene,logic: supportTicketSceneLogic,productKey: ProductKey.CONVERSATIONS,- paramsToProps: ({ params: { ticketId } }) => ({ ticketId, id: ticketId || 'new' }),+ // `id` must match supportTicketSceneLogic's `key((props) => props.id)` so the logic instance+ // App.tsx binds via BindLogic (and that the side panel context reads) is the same keyed+ // instance the component builds directly — otherwise the side panel reads a never-populated+ // logic instance and the access control tab never appears.+ paramsToProps: ({ params: { ticketId } }) => ({ ticketId: ticketId || 'new', id: ticketId || 'new' }),}// The rendered label is "<Send|Attach> and set <statusLabel>", depending on the private note checkbox@@ -150,6 +156,13 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem}[emailReplyBlockedReason]: undefined+ const sendDisabledReason =+ getAccessControlDisabledReason(+ AccessControlResourceType.Ticket,+ AccessControlLevel.Editor,+ ticket?.user_access_level+ ) ?? undefined+const chatPanelRef = useRef<HTMLDivElement>(null)const resizerLogicProps: ResizerLogicProps = {@@ -232,11 +245,13 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemsendAndSetStatusOptions={ticket ? SEND_AND_SET_STATUS_OPTIONS : undefined}unsavedTicketChanges={unsavedTicketChanges}replyDisabledReason={replyDisabledReason}+ sendDisabledReason={sendDisabledReason}minHeight="min(400px, calc(100svh - 20rem))"maxHeight="calc(100svh - 20rem)"latestAiMessageId={latestAiMessage?.id ?? null}feedbackByMessageId={feedbackByMessageId}showAiReplyFeedback={aiSuggestionsEnabled}+ aiReplyFeedbackDisabledReason={sendDisabledReason}onSubmitAiReplyFeedback={submitAiReplyFeedback}/><div className="hidden lg:block">@@ -403,6 +418,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elemoptions={statusOptionsWithoutAll}onChange={(value: TicketStatus | null) => value && setStatus(value)}dropdownMatchSelectWidth={false}+ disabledReason={sendDisabledReason}/></div><div className="flex justify-between items-center">@@ -413,6 +429,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elemoptions={priorityOptions}onChange={(value: TicketPriority | null) => value && setPriority(value)}dropdownMatchSelectWidth={false}+ disabledReason={sendDisabledReason}/></div><div className="flex justify-between items-start">@@ -424,17 +441,23 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elemsize="xxsmall"type="tertiary"onClick={() => setAssignee({ type: 'user', id: user.id })}+ disabledReason={sendDisabledReason}><span className="text-accent">Assign to me</span></LemonButton>)}- <AssigneeSelect assignee={assignee} onChange={setAssignee}>+ <AssigneeSelect+ assignee={assignee}+ onChange={setAssignee}+ disabledReason={sendDisabledReason}+ >{(resolvedAssignee, isOpen) => (<LemonButtonsize="small"type="secondary"active={isOpen}sideIcon={<IconChevronDown />}+ disabledReason={sendDisabledReason}><span className="flex items-center gap-1"><AssigneeIconDisplay assignee={resolvedAssignee} size="small" />@@ -462,24 +485,40 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemselectionPeriod="upcoming"clearableplaceholder="Not snoozed"- buttonProps={{ size: 'small', type: 'secondary', fullWidth: false }}+ buttonProps={{+ size: 'small',+ type: 'secondary',+ fullWidth: false,+ disabledReason: sendDisabledReason,+ }}/></div><div className="flex justify-between items-center"><span className="text-muted-alt">Tags</span>- <TicketTags tags={tags} onChange={setTags} saving={false} />+ <TicketTags+ tags={tags}+ onChange={setTags}+ saving={false}+ disabledReason={sendDisabledReason}+ /></div></div><div className="mt-3 pt-3 border-t flex justify-end">- <LemonButton- type="primary"- size="small"- onClick={() => updateTicket()}- loading={ticketUpdating}- disabledReason={!hasUnsavedChanges ? 'No changes to save' : undefined}+ <AccessControlAction+ resourceType={AccessControlResourceType.Ticket}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={ticket?.user_access_level}>- Save changes- </LemonButton>+ <LemonButton+ type="primary"+ size="small"+ onClick={() => updateTicket()}+ loading={ticketUpdating}+ disabledReason={!hasUnsavedChanges ? 'No changes to save' : undefined}+ >+ Save changes+ </LemonButton>+ </AccessControlAction></div></LemonCard>diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.tsindex 64c1334f39df..b003626f6aec 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts@@ -26,6 +26,7 @@ import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'+import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'import { impersonationNoticeLogic } from '~/layout/navigation/ImpersonationNotice/impersonationNoticeLogic'import api from '~/lib/api'import { PERSON_DISPLAY_NAME_COLUMN_NAME } from '~/lib/constants'@@ -204,6 +205,7 @@ export interface supportTicketSceneLogicValues {previousTicketsLoading: booleanpriority: TicketPriority | nullreplyRecipientDescription: string+ sidePanelContext: SidePanelSceneContext | nullsnoozedUntil: string | nullstatus: TicketStatus | nulltags: string[]@@ -435,6 +437,7 @@ export interface supportTicketSceneLogicMeta {eventsQuery: (ticket: Ticket | null) => DataTableNode | nullexceptionsQuery: (ticket: Ticket | null) => DataTableNode | nulllatestAiMessage: (chatMessages: ChatMessage[]) => ChatMessage | null+ sidePanelContext: (ticket: Ticket | null) => SidePanelSceneContext | null}}@@ -961,6 +964,17 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([return null},],+ [SIDE_PANEL_CONTEXT_KEY]: [+ (s) => [s.ticket],+ (ticket: Ticket | null): SidePanelSceneContext | null => {+ return ticket?.id+ ? {+ access_control_resource: 'ticket',+ access_control_resource_id: `${ticket.id}`,+ }+ : null+ },+ ],}),listeners(({ actions, values, props, cache }) => ({loadTicket: async () => {diff --git a/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx b/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsxindex 2b44ac4ae3a4..77981afea0fb 100644--- a/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx+++ b/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx@@ -65,10 +65,13 @@ interface SupportTicketsTableProps {}function SupportTicketsBulkActions(): JSX.Element {- const { selectedTicketIds, selectedTickets, bulkUpdating } = useValues(supportTicketsSceneLogic)+ const { selectedTicketIds, selectedTickets, editableSelectedTicketIds, bulkUpdating } =+ useValues(supportTicketsSceneLogic)const { bulkUpdateStatus } = useActions(supportTicketsSceneLogic)const hasSelection = selectedTicketIds.length > 0+ const editableTicketIds = editableSelectedTicketIds+ const hasRestrictedSelection = editableTicketIds.length < selectedTicketIds.lengthconst selectedStatuses = selectedTickets.map((t) => t.status)const currentStatus = selectedStatuses.reduce<TicketStatus | 'mixed' | null>((acc, s) => {if (acc === null) {@@ -80,15 +83,28 @@ function SupportTicketsBulkActions(): JSX.Element {return (<LemonSelectonChange={(value) => {- if (!value || value === currentStatus) {+ if (!value || value === currentStatus || editableTicketIds.length === 0) {return}- bulkUpdateStatus(selectedTicketIds, value as TicketStatus)+ bulkUpdateStatus(editableTicketIds, value as TicketStatus)}}value={null}placeholder="Mark as"loading={bulkUpdating}- disabledReason={!hasSelection ? 'Select tickets first' : bulkUpdating ? 'Updating…' : undefined}+ disabledReason={+ !hasSelection+ ? 'Select tickets first'+ : bulkUpdating+ ? 'Updating…'+ : editableTicketIds.length === 0+ ? "You don't have edit access to any of the selected tickets"+ : undefined+ }+ tooltip={+ hasRestrictedSelection && editableTicketIds.length > 0+ ? `${selectedTicketIds.length - editableTicketIds.length} selected ticket(s) will be skipped because you don't have edit access to them`+ : undefined+ }options={statusOptionsWithoutAll.map((o) => ({ value: o.value, label: o.label }))}size="small"/>diff --git a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.test.ts b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.test.tsindex 22f9bf7227a0..abe128c440f3 100644--- a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.test.ts+++ b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.test.ts@@ -5,11 +5,33 @@ import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { AccessControlLevel } from '~/types'import { MAX_ASSIGNEE_FILTER_ENTRIES } from '../../components/Assignee'-import { normalizeAssigneeFilter, type SavedTicketView, type TicketViewFilters } from '../../types'+import { normalizeAssigneeFilter, type SavedTicketView, type Ticket, type TicketViewFilters } from '../../types'import { supportTicketsSceneLogic } from './supportTicketsSceneLogic'+function makeTicket(id: string, userAccessLevel?: AccessControlLevel): Ticket {+ return {+ id,+ ticket_number: 1,+ distinct_id: `distinct-${id}`,+ status: 'open',+ channel_source: 'email',+ anonymous_traits: {},+ identity_verified: false,+ ai_resolved: false,+ created_at: '2026-06-12T00:00:00Z',+ updated_at: '2026-06-12T00:00:00Z',+ message_count: 1,+ last_message_at: '2026-06-12T00:00:00Z',+ last_message_text: 'Hello',+ unread_team_count: 0,+ unread_customer_count: 0,+ user_access_level: userAccessLevel,+ }+}+function makeSavedView(shortId: string, filters: TicketViewFilters = {}): SavedTicketView {return {id: shortId,@@ -33,6 +55,55 @@ describe('supportTicketsSceneLogic', () => {localStorage.clear()})+ describe('editable selected ticket IDs', () => {+ let logic: ReturnType<typeof supportTicketsSceneLogic.build>++ beforeEach(() => {+ useMocks({+ get: {+ '/api/projects/:team_id/conversations/tickets/': () => [200, { results: [], count: 0 }],+ },+ })+ initKeaTests()+ logic = supportTicketsSceneLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ // Regression: bulk status updates must only ever be sent for tickets the caller can edit.+ // The backend already enforces this (silently skipping non-editable IDs), but a selection+ // mixing editable and view-only tickets should be filtered client-side too, not just relayed+ // wholesale to the API.+ it('filters out tickets the user cannot edit at the object level', () => {+ const editable = makeTicket('editable', AccessControlLevel.Editor)+ const viewerOnly = makeTicket('viewer-only', AccessControlLevel.Viewer)+ const noAccess = makeTicket('no-access', AccessControlLevel.None)+ const unset = makeTicket('unset')++ expectLogic(logic, () => {+ logic.actions.setTickets([editable, viewerOnly, noAccess, unset])+ logic.actions.setSelectedTicketIds([editable.id, viewerOnly.id, noAccess.id, unset.id])+ }).toMatchValues({+ editableSelectedTicketIds: [editable.id, unset.id],+ })+ })++ it('includes every selected ticket when none are access-restricted', () => {+ const a = makeTicket('a', AccessControlLevel.Editor)+ const b = makeTicket('b', AccessControlLevel.Manager)++ expectLogic(logic, () => {+ logic.actions.setTickets([a, b])+ logic.actions.setSelectedTicketIds([a.id, b.id])+ }).toMatchValues({+ editableSelectedTicketIds: [a.id, b.id],+ })+ })+ })+describe('normalizeAssigneeFilter', () => {it.each([['legacy "all"', 'all', []],diff --git a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.tsindex dc3af88295f1..a1ec946aa615 100644--- a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts+++ b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts@@ -17,10 +17,11 @@ import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'import { Sorting } from 'lib/lemon-ui/LemonTable/sorting'+import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'import { objectsEqual } from 'lib/utils/objects'import { teamLogic } from 'scenes/teamLogic'-import { TeamType } from '~/types'+import { AccessControlLevel, AccessControlResourceType, TeamType } from '~/types'import { conversationsViewsRetrieve } from '../../generated/api'import { normalizeAssigneeFilter } from '../../types'@@ -209,6 +210,7 @@ export interface supportTicketsSceneLogicValues {dateTo: string | null} | nulldateTo: string | null+ editableSelectedTicketIds: string[]hasActiveFilters: booleanorderBy: stringpriorityFilter: TicketPriority[]@@ -339,6 +341,7 @@ export interface supportTicketsSceneLogicMeta {aiEnabled: (currentTeam: TeamType | null | import('~/types').TeamPublicType) => booleanorderBy: (sorting: Sorting | null) => stringselectedTickets: (tickets: Ticket[], selectedTicketIds: string[]) => Ticket[]+ editableSelectedTicketIds: (selectedTickets: Ticket[]) => string[]assigneeFilterEntries: (assigneeFilter: AssigneeFilterEntry[]) => AssigneeFilterEntry[]hasActiveFilters: (statusFilter: TicketStatus[],@@ -597,6 +600,21 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([return tickets.filter((t) => idSet.has(t.id))},],+ editableSelectedTicketIds: [+ (s) => [s.selectedTickets],+ (selectedTickets: Ticket[]): string[] =>+ selectedTickets+ .filter(+ (ticket) =>+ !ticket.user_access_level ||+ accessLevelSatisfied(+ AccessControlResourceType.Ticket,+ ticket.user_access_level,+ AccessControlLevel.Editor+ )+ )+ .map((ticket) => ticket.id),+ ],assigneeFilterEntries: [(s) => [s.assigneeFilter],(assigneeFilter: AssigneeFilterEntry[]): AssigneeFilterEntry[] => normalizeAssigneeFilter(assigneeFilter),diff --git a/products/conversations/frontend/types.ts b/products/conversations/frontend/types.tsindex 94d52f4140b6..bf2c575e25e7 100644--- a/products/conversations/frontend/types.ts+++ b/products/conversations/frontend/types.ts@@ -1,5 +1,7 @@import type { Sorting } from 'lib/lemon-ui/LemonTable/sorting'+import type { AccessControlLevel } from '~/types'+import { MAX_ASSIGNEE_FILTER_ENTRIES } from './components/Assignee'import type { AssigneeFilterEntry, TicketAssignee } from './components/Assignee'@@ -180,6 +182,8 @@ export interface Ticket {person?: TicketPerson | nulltags?: string[]ai_triage?: AITriage+ /** The effective access level the current user has for this ticket. */+ user_access_level?: AccessControlLevel}export interface ConversationTicket {diff --git a/products/slack_app/backend/slack_link_unfurl.py b/products/slack_app/backend/slack_link_unfurl.pyindex 383ce033f7aa..362ab3b39324 100644--- a/products/slack_app/backend/slack_link_unfurl.py+++ b/products/slack_app/backend/slack_link_unfurl.py@@ -254,9 +254,9 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:Unfurl PostHog insight, dashboard, and support ticket links with title and description.Scope is always the Slack-connected project (`integration.team`); `resolve_slack_user` enforces- that the sharer can access it. Insights/dashboards add a per-resource access-control check;- tickets have no per-object ACL, but a link naming a different project is refused (ticket numbers- are per-project, so resolving by number could otherwise surface the wrong ticket).+ that the sharer can access it. Insights, dashboards, and tickets add a per-resource+ access-control check. Ticket links naming a different project are also refused because ticket+ numbers are per-project and could otherwise resolve to the wrong ticket."""slack = SlackIntegration(integration)channel = event.get("channel")@@ -338,9 +338,8 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:if url_team_id is not None and url_team_id != team.pk:continueticket = _find_ticket(team.pk, ref)- if not ticket:+ if not ticket or not uac.check_access_level_for_object(ticket, required_level="viewer"):continue- # Tickets have no per-object ACL — any member of the connected team may view them.unfurls[raw_url] = _ticket_unfurl_payload(url=raw_url,ticket=ticket,diff --git a/products/slack_app/backend/tests/test_link_unfurl.py b/products/slack_app/backend/tests/test_link_unfurl.pyindex a7559130493b..32aa02bf087e 100644--- a/products/slack_app/backend/tests/test_link_unfurl.py+++ b/products/slack_app/backend/tests/test_link_unfurl.py@@ -8,7 +8,9 @@ from django.utils import timezonefrom parameterized import parameterized+from posthog.constants import AvailableFeaturefrom posthog.helpers.slack_scopes import REQUIRED_SLACK_SCOPES+from posthog.models import Userfrom posthog.models.comment import Commentfrom posthog.models.integration import Integrationfrom posthog.models.organization import Organization@@ -26,6 +28,8 @@ from products.slack_app.backend.slack_link_unfurl import (parse_posthog_resource_link,)+from ee.models.rbac.access_control import AccessControl+class TestParsePosthogResourceLink:def test_project_insight(self):@@ -243,6 +247,43 @@ class TestHandlePosthogLinkUnfurl(APIBaseTest):assert "Requested by:* [email protected]" in textassert "New" in text # default status, humanized+ @parameterized.expand([("resource",), ("object",)])+ @patch("products.slack_app.backend.api.resolve_slack_user")+ @patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")+ def test_skips_ticket_without_viewer_access(+ self,+ denied_scope: str,+ mock_slack_integration_class: MagicMock,+ mock_resolve: MagicMock,+ ) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ member = User.objects.create_and_join(self.organization, "[email protected]", "password")+ ticket = Ticket.objects.create(team=self.team, ticket_number=5, widget_session_id="s5", distinct_id="d5")+ if denied_scope == "resource":+ AccessControl.objects.create(resource="ticket", team=self.team, access_level="none")+ else:+ AccessControl.objects.create(+ resource="ticket",+ resource_id=str(ticket.id),+ organization_member=member.organization_memberships.get(organization=self.organization),+ team=self.team,+ access_level="none",+ )+ mock_resolve.return_value = MagicMock(user=member)+ mock_client = MagicMock()+ mock_slack_integration_class.return_value.client = mock_client++ url = f"http://testserver/project/{self.team.pk}/support/tickets/{ticket.ticket_number}"+ handle_posthog_link_unfurl(+ {"channel": "C1", "message_ts": "1.2", "user": "U1", "links": [{"url": url}]},+ self.integration,+ )++ mock_client.chat_unfurl.assert_not_called()+@patch("products.slack_app.backend.api.resolve_slack_user")@patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")def test_skips_ticket_from_another_project(diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c3610d8248b6..8e4d1416f3ac 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -45746,7 +45746,7 @@ export namespace Schemas {}/**- * Serializer mixin that handles tags for objects.+ * Mixin for serializers to add user access control fields*/export interface Ticket {readonly id: string;@@ -45832,6 +45832,11 @@ export namespace Schemas {readonly organization_id_source: string | null;readonly person: TicketPerson | null;tags?: unknown[];+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level: string | null;}export interface PaginatedTicketList {@@ -53697,7 +53702,7 @@ export namespace Schemas {}/**- * Serializer mixin that handles tags for objects.+ * Mixin for serializers to add user access control fields*/export interface PatchedTicket {readonly id?: string;@@ -53783,6 +53788,11 @@ export namespace Schemas {readonly organization_id_source?: string | null;readonly person?: TicketPerson | null;tags?: unknown[];+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level?: string | null;}/**diff --git a/services/mcp/src/generated/conversations/api.ts b/services/mcp/src/generated/conversations/api.tsindex a71a898f0e31..d125829c82ba 100644--- a/services/mcp/src/generated/conversations/api.ts+++ b/services/mcp/src/generated/conversations/api.ts@@ -164,7 +164,7 @@ export const ConversationsTicketsPartialUpdateBody = /* @__PURE__ */ zodsnoozed_until: zod.iso.datetime({ offset: true }).nullish(),tags: zod.array(zod.unknown()).optional(),})- .describe('Serializer mixin that handles tags for objects.')+ .describe('Mixin for serializers to add user access control fields')/*** Return the message thread for a ticket, ordered chronologically (paginated).