: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
chore(tasks): remove the retired PostHog Desktop seats proxy (#94644)
Roy Cohen743415ee32ae
diff --git a/products/tasks/backend/presentation/views/seat_api.py b/products/tasks/backend/presentation/views/seat_api.pydeleted file mode 100644index e8fe9a9381f4..000000000000--- a/products/tasks/backend/presentation/views/seat_api.py+++ /dev/null@@ -1,405 +0,0 @@-import re-from concurrent.futures import ThreadPoolExecutor, as_completed-from datetime import datetime-from typing import Any, cast--import requests-import structlog-from drf_spectacular.utils import extend_schema-from rest_framework import status, viewsets-from rest_framework.authentication import SessionAuthentication-from rest_framework.decorators import action-from rest_framework.exceptions import NotAuthenticated, ParseError, PermissionDenied-from rest_framework.permissions import IsAuthenticated-from rest_framework.request import Request-from rest_framework.response import Response--from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication-from posthog.cloud_utils import get_cached_instance_license-from posthog.models.organization import Organization, OrganizationMembership-from posthog.models.user import User--# TODO: Centralize billing proxy through BillingManager (ee/billing/) to avoid-# duplicating auth header construction and keep all billing communication in one place-from ee.billing.billing_manager import build_billing_token-from ee.settings import BILLING_SERVICE_URL--PRO_PLAN_PREFIXES = ("posthog-code-200", "posthog-code-pro-")-RETIRED_SEAT_PRODUCT_MESSAGE = (- "You can no longer create, upgrade, or reactivate PostHog Desktop seats. "- "PostHog Desktop with usage-based billing launched on July 16, 2026, "- "and existing seats expire on the same date."-)-RETIRED_SEAT_PRODUCTS = {"posthog_code": RETIRED_SEAT_PRODUCT_MESSAGE}---def _seat_priority(seat: dict[str, Any]) -> tuple[bool, int, float]:- # Tuple comparison: active (True > False) first, then tier, then- # earliest created_at wins ties (oldest seat is the stable pick).- # `canceling` is treated as currently active because the seat is still in- # effect until its `active_until` timestamp (notably during the alpha→free- # migration window where alpha seats are flipped to `canceling`).- active = seat.get("status") in ("active", "canceling")- plan_key = seat.get("plan_key") or ""- created_at = seat.get("created_at") or ""- try:- ts = datetime.fromisoformat(created_at).timestamp()- except (ValueError, TypeError):- ts = float("inf")- if any(plan_key.startswith(p) for p in PRO_PLAN_PREFIXES):- return (active, 2, -ts)- if plan_key:- return (active, 1, -ts)- return (active, 0, -ts)---logger = structlog.get_logger(__name__)--REQUEST_TIMEOUT_SECONDS = 30-_SAFE_PK_PATTERN = re.compile(r"^[a-zA-Z0-9_-]+$")---def _is_org_admin(user: Any) -> bool:- org = user.organization- if not org:- return False- return OrganizationMembership.objects.filter(- user=user, organization=org, level__gte=OrganizationMembership.Level.ADMIN- ).exists()---@extend_schema(exclude=True)-class SeatViewSet(viewsets.ViewSet):- """- Proxy for seat management through the billing service.-- All endpoints resolve ``me`` in the URL to the requesting user's- ``distinct_id``, build a billing JWT and forward the request to the- billing service's ``/api/v2/seats/`` endpoints.-- Successful responses that contain seat data are unwrapped so the- client receives the seat object directly (not the billing envelope).- Error responses are forwarded as-is.- """-- authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]- permission_classes = [IsAuthenticated]- http_method_names = ["get", "post", "patch", "delete", "head", "options"]-- # ------------------------------------------------------------------- # Helpers- # -------------------------------------------------------------------- def _get_billing_headers(self, request: Request) -> dict[str, str] | None:- user = cast(User, request.user)- org = user.organization- if not org:- return None- return self._get_billing_headers_for_org(user, org)-- def _get_billing_headers_for_org(self, user: User, org: Organization) -> dict[str, str] | None:- license = get_cached_instance_license()- if not license:- return None- try:- token = build_billing_token(license, org, user)- except NotAuthenticated:- logger.warning("User not a member of organization", user_id=user.id, org_id=str(org.id))- return None- except Exception:- logger.exception("Failed to build billing token", user_id=user.id, org_id=str(org.id))- return None- return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}-- @staticmethod- def _resolve_distinct_id(pk: str | None, request: Request) -> str:- if pk is None:- raise ParseError("pk is required")- if pk == "me":- return str(cast(User, request.user).distinct_id)- if not _SAFE_PK_PATTERN.match(pk):- raise ParseError("Invalid identifier format")- return pk-- def _forward_response(self, billing_response: requests.Response | None, extract_seat: bool = True) -> Response:- """Convert a billing service response to a DRF Response.-- For successful responses that contain a ``seat`` key the seat- object is returned directly so the client doesn't need to know- about the billing envelope. Error responses pass through as-is.- """- if billing_response is None:- return Response({"detail": "Billing service unavailable"}, status=status.HTTP_502_BAD_GATEWAY)-- if billing_response.status_code == 204:- return Response(status=status.HTTP_204_NO_CONTENT)-- try:- data = billing_response.json()- except ValueError:- return Response({"detail": "Invalid response from billing service"}, status=status.HTTP_502_BAD_GATEWAY)-- if billing_response.ok and extract_seat and isinstance(data, dict) and "seat" in data:- return Response(data["seat"], status=billing_response.status_code)-- return Response(data, status=billing_response.status_code)-- def _billing_request(- self,- method: str,- path: str,- headers: dict[str, str],- json_body: Any = None,- query_params: dict[str, str] | None = None,- ) -> requests.Response | None:- url = f"{BILLING_SERVICE_URL}{path}"- try:- return requests.request(- method=method,- url=url,- headers=headers,- json=json_body,- params=query_params,- timeout=REQUEST_TIMEOUT_SECONDS,- )- except requests.RequestException:- logger.exception("Billing service request failed", path=path, method=method)- return None-- def _require_admin(self, request: Request) -> None:- if not _is_org_admin(request.user):- raise PermissionDenied("Only organization admins can perform this action.")-- def _require_org_member(self, request: Request, distinct_id: str) -> None:- org = cast(User, request.user).organization- if (- not org- or not OrganizationMembership.objects.filter(- user__distinct_id=distinct_id,- organization=org,- ).exists()- ):- raise PermissionDenied("Target user is not a member of this organization.")-- def _resolve_and_check_membership(self, request: Request, pk: str | None) -> str:- distinct_id = self._resolve_distinct_id(pk, request)- if pk != "me":- self._require_org_member(request, distinct_id)- return distinct_id-- @staticmethod- def _retired_product_response(request: Request) -> Response | None:- product_key = request.data.get("product_key")- if not isinstance(product_key, str):- product_key = request.query_params.get("product_key")- message = RETIRED_SEAT_PRODUCTS.get(product_key) if isinstance(product_key, str) else None- if message is None:- return None- return Response(- {- "error": message,- "code": "seat_product_retired",- },- status=status.HTTP_410_GONE,- )-- @staticmethod- def _filtered_query_params(request: Request) -> dict[str, str]:- product_key = request.query_params.get("product_key", "")- if product_key:- return {"product_key": product_key}- return {}-- # ------------------------------------------------------------------- # Endpoints- # -------------------------------------------------------------------- def list(self, request: Request) -> Response:- """GET /api/seats/?product_key= -> GET /api/v2/seats/"""- self._require_admin(request)-- headers = self._get_billing_headers(request)- if not headers:- return Response({"detail": "No organization or license found"}, status=status.HTTP_400_BAD_REQUEST)-- resp = self._billing_request(- "GET",- "/api/v2/seats/",- headers,- query_params=self._filtered_query_params(request),- )- return self._forward_response(resp, extract_seat=False)-- def create(self, request: Request) -> Response:- """POST /api/seats/ -> POST /api/v2/seats/"""- body_distinct_id = request.data.get("user_distinct_id")- if not body_distinct_id:- return Response({"detail": "user_distinct_id is required"}, status=status.HTTP_400_BAD_REQUEST)- if not _SAFE_PK_PATTERN.match(str(body_distinct_id)):- return Response({"detail": "Invalid user_distinct_id format"}, status=status.HTTP_400_BAD_REQUEST)- if str(body_distinct_id) != str(cast(User, request.user).distinct_id):- self._require_admin(request)- self._require_org_member(request, str(body_distinct_id))-- if retired_response := self._retired_product_response(request):- return retired_response-- headers = self._get_billing_headers(request)- if not headers:- return Response({"detail": "No organization or license found"}, status=status.HTTP_400_BAD_REQUEST)-- resp = self._billing_request("POST", "/api/v2/seats/", headers, json_body=request.data)- return self._forward_response(resp)-- def retrieve(self, request: Request, pk: str | None = None) -> Response:- """GET /api/seats/me/ -> GET /api/v2/seats/{distinct_id}/?product_key=-- Pass ``?best=true`` to resolve the highest-tier seat across all- the user's organizations (only supported for ``pk=me``).- """- if pk != "me":- self._require_admin(request)-- use_best = request.query_params.get("best", "").lower() == "true"- if use_best and pk == "me":- return self._retrieve_best_seat(request)-- headers = self._get_billing_headers(request)- if not headers:- return Response({"detail": "No organization or license found"}, status=status.HTTP_400_BAD_REQUEST)-- distinct_id = self._resolve_and_check_membership(request, pk)- resp = self._billing_request(- "GET",- f"/api/v2/seats/{distinct_id}/",- headers,- query_params=self._filtered_query_params(request),- )- return self._forward_response(resp)-- def _retrieve_best_seat(self, request: Request) -> Response:- """Return the highest-tier seat across all the user's orgs.-- For single-org users this is a direct pass-through. For multi-org- users, billing requests fan out in parallel via ThreadPoolExecutor- (capped at 5 workers) and the best seat is selected by- ``_seat_priority``.- """- user = cast(User, request.user)- distinct_id = str(user.distinct_id)- query_params = self._filtered_query_params(request)-- memberships = OrganizationMembership.objects.filter(user=user).select_related("organization")- orgs = [m.organization for m in memberships if m.organization is not None]-- if not orgs:- return Response({"detail": "No organization found"}, status=status.HTTP_400_BAD_REQUEST)-- if len(orgs) == 1:- org = orgs[0]- headers = self._get_billing_headers_for_org(user, org)- if not headers:- return Response({"detail": "No license found"}, status=status.HTTP_400_BAD_REQUEST)- resp = self._billing_request("GET", f"/api/v2/seats/{distinct_id}/", headers, query_params=query_params)- drf_resp = self._forward_response(resp)- if not 200 <= drf_resp.status_code < 300 or not isinstance(drf_resp.data, dict):- return drf_resp- data = {**drf_resp.data, "organization_id": str(org.id), "organization_name": org.name}- return Response(data)-- def fetch_seat(org: Organization) -> tuple[Organization, Response]:- headers = self._get_billing_headers_for_org(user, org)- resp = (- self._billing_request("GET", f"/api/v2/seats/{distinct_id}/", headers, query_params=query_params)- if headers- else None- )- return (org, self._forward_response(resp))-- results: list[tuple[Organization, dict[str, Any]]] = []- any_lookup_failed = False- with ThreadPoolExecutor(max_workers=min(len(orgs), 5)) as pool:- futures = {pool.submit(fetch_seat, org): org for org in orgs}- for future in as_completed(futures):- try:- org, drf_resp = future.result()- except Exception:- logger.exception("fetch_seat_crashed", org_id=str(futures[future].id))- any_lookup_failed = True- continue- if 200 <= drf_resp.status_code < 300 and isinstance(drf_resp.data, dict):- results.append((org, drf_resp.data))- elif drf_resp.status_code != status.HTTP_404_NOT_FOUND:- logger.warning("fetch_seat_failed", org_id=str(org.id), status_code=drf_resp.status_code)- any_lookup_failed = True-- if not results:- if any_lookup_failed:- return Response({"detail": "Seat lookup incomplete"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)- return Response(status=status.HTTP_404_NOT_FOUND)-- best_org, best = max(results, key=lambda r: _seat_priority(r[1]))- best["organization_id"] = str(best_org.id)- best["organization_name"] = best_org.name- return Response(best)-- def partial_update(self, request: Request, pk: str | None = None) -> Response:- """PATCH /api/seats/me/ -> PATCH /api/v2/seats/{distinct_id}/"""- if pk != "me":- self._require_admin(request)-- distinct_id = self._resolve_and_check_membership(request, pk)- if retired_response := self._retired_product_response(request):- return retired_response-- headers = self._get_billing_headers(request)- if not headers:- return Response({"detail": "No organization or license found"}, status=status.HTTP_400_BAD_REQUEST)-- resp = self._billing_request(- "PATCH",- f"/api/v2/seats/{distinct_id}/",- headers,- json_body=request.data,- )- return self._forward_response(resp)-- def destroy(self, request: Request, pk: str | None = None) -> Response:- """DELETE /api/seats/me/?product_key= -> DELETE /api/v2/seats/{distinct_id}/?product_key="""- if pk != "me":- self._require_admin(request)-- headers = self._get_billing_headers(request)- if not headers:- return Response({"detail": "No organization or license found"}, status=status.HTTP_400_BAD_REQUEST)-- distinct_id = self._resolve_and_check_membership(request, pk)- resp = self._billing_request(- "DELETE",- f"/api/v2/seats/{distinct_id}/",- headers,- query_params=self._filtered_query_params(request),- )- return self._forward_response(resp, extract_seat=False)-- @action(detail=True, methods=["post"], url_path="reactivate")- def reactivate(self, request: Request, pk: str | None = None) -> Response:- """POST /api/seats/me/reactivate/ -> POST /api/v2/seats/{distinct_id}/reactivate/"""- if pk != "me":- self._require_admin(request)-- distinct_id = self._resolve_and_check_membership(request, pk)- if retired_response := self._retired_product_response(request):- return retired_response-- headers = self._get_billing_headers(request)- if not headers:- return Response({"detail": "No organization or license found"}, status=status.HTTP_400_BAD_REQUEST)-- resp = self._billing_request(- "POST",- f"/api/v2/seats/{distinct_id}/reactivate/",- headers,- json_body=request.data,- )- return self._forward_response(resp)diff --git a/products/tasks/backend/routes.py b/products/tasks/backend/routes.pyindex 8e961a470a10..8ae9d7af3eee 100644--- a/products/tasks/backend/routes.py+++ b/products/tasks/backend/routes.py@@ -3,7 +3,6 @@ from posthog.api.routing import RouterRegistryimport products.tasks.backend.presentation.views.api as tasksimport products.tasks.backend.presentation.views.loops as loopsimport products.tasks.backend.presentation.views.desktop as desktop-import products.tasks.backend.presentation.views.seat_api as seatsimport products.tasks.backend.presentation.views.config_api as configimport products.tasks.backend.presentation.views.channels_api as channelsimport products.tasks.backend.presentation.views.desktop_access as desktop_access@@ -60,5 +59,4 @@ def register_routes(routers: RouterRegistry) -> None:routers.root.register(r"code/sandbox-pricing", sandbox_pricing.SandboxComputePricingViewSet, "sandbox_compute_pricing")- routers.root.register(r"seats", seats.SeatViewSet, "seats")routers.root.register(r"code/internal/task_usage", task_usage.InternalTaskUsageViewSet, "internal_task_usage")diff --git a/products/tasks/backend/tests/test_seat_api.py b/products/tasks/backend/tests/test_seat_api.pydeleted file mode 100644index 292e86fec413..000000000000--- a/products/tasks/backend/tests/test_seat_api.py+++ /dev/null@@ -1,728 +0,0 @@-import json-from typing import ClassVar, Protocol--from unittest.mock import MagicMock, patch--from django.test import TestCase--from parameterized import parameterized-from rest_framework import status-from rest_framework.exceptions import NotAuthenticated-from rest_framework.test import APIClient--from posthog.models import Organization, OrganizationMembership, Team, User-from posthog.models.personal_api_key import PersonalAPIKey-from posthog.models.utils import generate_random_token_personal, hash_key_value--MOCK_BILLING_TOKEN = "mock-billing-jwt-token"-MOCK_SEAT = {- "id": "seat_123",- "user_distinct_id": "user-abc",- "product_key": "posthog_code",- "plan_key": "posthog-code-200-20260301",- "status": "active",- "end_reason": None,- "created_at": "2026-04-01T00:00:00Z",- "active_until": None,- "active_from": "2026-04-01T00:00:00Z",-}---class _JsonTestResponse(Protocol):- status_code: int-- def json(self) -> dict[str, object]: ...---def _billing_response(data=None, status_code=200, ok=True):- resp = MagicMock()- resp.status_code = status_code- resp.ok = ok- resp.json.return_value = data if data is not None else {}- return resp---class BaseSeatAPITest(TestCase):- client: APIClient- organization: ClassVar[Organization]- team: ClassVar[Team]- user: ClassVar[User]- admin_user: ClassVar[User]- external_user: ClassVar[User]-- @classmethod- def setUpTestData(cls):- cls.organization = Organization.objects.create(name="Test Org")- cls.team = Team.objects.create(organization=cls.organization, name="Test Team")-- cls.admin_user = User.objects.create_user(email="[email protected]", first_name="Admin", password="password")- cls.organization.members.add(cls.admin_user)- OrganizationMembership.objects.filter(user=cls.admin_user, organization=cls.organization).update(- level=OrganizationMembership.Level.ADMIN- )-- cls.user = User.objects.create_user(email="[email protected]", first_name="Member", password="password")- cls.organization.members.add(cls.user)-- cls.external_user = User.objects.create_user(- email="[email protected]", first_name="External", password="password"- )-- def setUp(self):- self.client = APIClient()-- def _auth_as_admin(self):- self.client.force_authenticate(self.admin_user)-- def _auth_as_member(self):- self.client.force_authenticate(self.user)---@patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)-@patch("products.tasks.backend.presentation.views.seat_api.get_cached_instance_license", return_value=MagicMock())-class TestSeatAPIAdminPermissions(BaseSeatAPITest):- """Non-admin users should be blocked from list and non-me operations."""-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_list_requires_admin(self, mock_request, _mock_license, _mock_token):- self._auth_as_member()- response = self.client.get("/api/seats/?product_key=posthog_code")- assert response.status_code == status.HTTP_403_FORBIDDEN-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_list_allowed_for_admin(self, mock_request, _mock_license, _mock_token):- mock_request.return_value = _billing_response({"seats": [MOCK_SEAT]})- self._auth_as_admin()- response = self.client.get("/api/seats/?product_key=posthog_code")- assert response.status_code == status.HTTP_200_OK-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_retrieve_other_user_requires_admin(self, mock_request, _mock_license, _mock_token):- self._auth_as_member()- response = self.client.get(f"/api/seats/{self.admin_user.distinct_id}/?product_key=posthog_code")- assert response.status_code == status.HTTP_403_FORBIDDEN-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_retrieve_me_allowed_for_member(self, mock_request, _mock_license, _mock_token):- mock_request.return_value = _billing_response({"seat": MOCK_SEAT})- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code")- assert response.status_code == status.HTTP_200_OK-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_delete_other_user_requires_admin(self, mock_request, _mock_license, _mock_token):- self._auth_as_member()- response = self.client.delete(f"/api/seats/{self.admin_user.distinct_id}/?product_key=posthog_code")- assert response.status_code == status.HTTP_403_FORBIDDEN-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_patch_other_user_requires_admin(self, mock_request, _mock_license, _mock_token):- self._auth_as_member()- response = self.client.patch(- f"/api/seats/{self.admin_user.distinct_id}/",- {"product_key": "posthog_code", "plan_key": "posthog-code-200-20260301"},- format="json",- )- assert response.status_code == status.HTTP_403_FORBIDDEN-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_create_without_user_distinct_id_returns_400(self, mock_request, _mock_license, _mock_token):- self._auth_as_member()- response = self.client.post(- "/api/seats/",- {"product_key": "posthog_code", "plan_key": "posthog-code-free-20260301"},- format="json",- )- assert response.status_code == status.HTTP_400_BAD_REQUEST- assert response.json()["detail"] == "user_distinct_id is required"-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_create_for_other_user_requires_admin(self, mock_request, _mock_license, _mock_token):- self._auth_as_member()- response = self.client.post(- "/api/seats/",- {"product_key": "posthog_code", "plan_key": "posthog-code-free-20260301", "user_distinct_id": "other-id"},- format="json",- )- assert response.status_code == status.HTTP_403_FORBIDDEN-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_create_for_self_allowed_for_member(self, mock_request, _mock_license, _mock_token):- mock_request.return_value = _billing_response({"seat": MOCK_SEAT})- self._auth_as_member()- response = self.client.post(- "/api/seats/",- {- "product_key": "other_product",- "plan_key": "other-plan",- "user_distinct_id": str(self.user.distinct_id),- },- format="json",- )- assert response.status_code == status.HTTP_200_OK-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_reactivate_other_user_requires_admin(self, mock_request, _mock_license, _mock_token):- self._auth_as_member()- response = self.client.post(f"/api/seats/{self.admin_user.distinct_id}/reactivate/", format="json")- assert response.status_code == status.HTTP_403_FORBIDDEN-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_retrieve_non_org_member_rejected(self, mock_request, _mock_license, _mock_token):- self._auth_as_admin()- response = self.client.get(f"/api/seats/{self.external_user.distinct_id}/?product_key=posthog_code")- assert response.status_code == status.HTTP_403_FORBIDDEN-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_patch_non_org_member_rejected(self, mock_request, _mock_license, _mock_token):- self._auth_as_admin()- response = self.client.patch(- f"/api/seats/{self.external_user.distinct_id}/",- {"product_key": "posthog_code", "plan_key": "posthog-code-200-20260301"},- format="json",- )- assert response.status_code == status.HTTP_403_FORBIDDEN-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_delete_non_org_member_rejected(self, mock_request, _mock_license, _mock_token):- self._auth_as_admin()- response = self.client.delete(f"/api/seats/{self.external_user.distinct_id}/?product_key=posthog_code")- assert response.status_code == status.HTTP_403_FORBIDDEN-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_create_for_non_org_member_rejected(self, mock_request, _mock_license, _mock_token):- self._auth_as_admin()- response = self.client.post(- "/api/seats/",- {- "product_key": "posthog_code",- "plan_key": "posthog-code-free-20260301",- "user_distinct_id": str(self.external_user.distinct_id),- },- format="json",- )- assert response.status_code == status.HTTP_403_FORBIDDEN-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_reactivate_non_org_member_rejected(self, mock_request, _mock_license, _mock_token):- self._auth_as_admin()- response = self.client.post(- f"/api/seats/{self.external_user.distinct_id}/reactivate/",- {"product_key": "posthog_code"},- format="json",- )- assert response.status_code == status.HTTP_403_FORBIDDEN---@patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)-@patch("products.tasks.backend.presentation.views.seat_api.get_cached_instance_license", return_value=MagicMock())-class TestSeatAPIMeResolution(BaseSeatAPITest):- """``me`` in the URL should resolve to the authenticated user's distinct_id."""-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_retrieve_me_resolves_distinct_id(self, mock_request, _mock_license, _mock_token):- mock_request.return_value = _billing_response({"seat": MOCK_SEAT})- self._auth_as_member()- self.client.get("/api/seats/me/?product_key=posthog_code")- _, kwargs = mock_request.call_args- assert str(self.user.distinct_id) in kwargs["url"]-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_delete_me_resolves_distinct_id(self, mock_request, _mock_license, _mock_token):- mock_request.return_value = _billing_response(status_code=204)- self._auth_as_member()- self.client.delete("/api/seats/me/?product_key=posthog_code")- _, kwargs = mock_request.call_args- assert str(self.user.distinct_id) in kwargs["url"]-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_patch_me_resolves_distinct_id(self, mock_request, _mock_license, _mock_token):- mock_request.return_value = _billing_response({"seat": MOCK_SEAT})- self._auth_as_member()- self.client.patch(- "/api/seats/me/",- {"product_key": "other_product", "plan_key": "other-plan"},- format="json",- )- _, kwargs = mock_request.call_args- assert str(self.user.distinct_id) in kwargs["url"]-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_reactivate_me_resolves_distinct_id(self, mock_request, _mock_license, _mock_token):- mock_request.return_value = _billing_response({"seat": MOCK_SEAT})- self._auth_as_member()- self.client.post("/api/seats/me/reactivate/", {"product_key": "other_product"}, format="json")- _, kwargs = mock_request.call_args- assert str(self.user.distinct_id) in kwargs["url"]---class TestSeatAPIRetiredProducts(BaseSeatAPITest):- def _assert_retired(self, response: _JsonTestResponse) -> None:- assert response.status_code == status.HTTP_410_GONE- assert response.json() == {- "error": (- "You can no longer create, upgrade, or reactivate PostHog Desktop seats. "- "PostHog Desktop with usage-based billing launched on July 16, 2026, "- "and existing seats expire on the same date."- ),- "code": "seat_product_retired",- }-- @parameterized.expand(- [- (- "create",- "POST",- "/api/seats/",- {- "product_key": "posthog_code",- "plan_key": "posthog-code-free-20260301",- "user_distinct_id": "me",- },- ),- (- "upgrade",- "PATCH",- "/api/seats/me/",- {"product_key": "posthog_code", "plan_key": "posthog-code-pro-200-20260301"},- ),- (- "reactivate",- "POST",- "/api/seats/me/reactivate/",- {"product_key": "posthog_code"},- ),- ]- )- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_posthog_code_mutation_is_rejected_locally(- self,- _name: str,- method: str,- path: str,- payload: dict[str, str],- mock_request: MagicMock,- ) -> None:- self._auth_as_member()- request_payload = payload.copy()- if request_payload.get("user_distinct_id") == "me":- request_payload["user_distinct_id"] = str(self.user.distinct_id)- response = self.client.generic(- method,- path,- json.dumps(request_payload),- content_type="application/json",- )-- self._assert_retired(response)- mock_request.assert_not_called()-- @parameterized.expand(- [- (- "create",- "POST",- "/api/seats/?product_key=posthog_code",- {- "plan_key": "posthog-code-free-20260301",- "user_distinct_id": "me",- },- ),- (- "upgrade",- "PATCH",- "/api/seats/me/?product_key=posthog_code",- {"plan_key": "posthog-code-pro-200-20260301"},- ),- (- "reactivate",- "POST",- "/api/seats/me/reactivate/?product_key=posthog_code",- {},- ),- ]- )- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_posthog_code_query_param_mutation_is_rejected_locally(- self,- _name: str,- method: str,- path: str,- payload: dict[str, str],- mock_request: MagicMock,- ) -> None:- self._auth_as_member()- request_payload = payload.copy()- if request_payload.get("user_distinct_id") == "me":- request_payload["user_distinct_id"] = str(self.user.distinct_id)- response = self.client.generic(- method,- path,- json.dumps(request_payload),- content_type="application/json",- )-- self._assert_retired(response)- mock_request.assert_not_called()---@patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)-@patch("products.tasks.backend.presentation.views.seat_api.get_cached_instance_license")-class TestSeatAPIBillingUnavailability(BaseSeatAPITest):- """Graceful handling when the billing service is unreachable or misconfigured."""-- def test_no_license_returns_400(self, mock_license, _mock_token):- mock_license.return_value = None- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code")- assert response.status_code == status.HTTP_400_BAD_REQUEST- assert response.json()["detail"] == "No organization or license found"-- @patch(- "products.tasks.backend.presentation.views.seat_api.requests.request",- side_effect=Exception("connection refused"),- )- def test_billing_request_exception_returns_502(self, mock_request, mock_license, _mock_token):- import requests as req-- mock_request.side_effect = req.ConnectionError("connection refused")- mock_license.return_value = MagicMock()- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code")- assert response.status_code == status.HTTP_502_BAD_GATEWAY-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_billing_invalid_json_returns_502(self, mock_request, mock_license, _mock_token):- mock_license.return_value = MagicMock()- billing_resp = MagicMock()- billing_resp.status_code = 200- billing_resp.ok = True- billing_resp.json.side_effect = ValueError("invalid json")- mock_request.return_value = billing_resp- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code")- assert response.status_code == status.HTTP_502_BAD_GATEWAY- assert response.json()["detail"] == "Invalid response from billing service"---@patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)-@patch("products.tasks.backend.presentation.views.seat_api.get_cached_instance_license", return_value=MagicMock())-class TestSeatAPIResponseUnwrapping(BaseSeatAPITest):- """Successful responses with a ``seat`` key are unwrapped; errors pass through."""-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_retrieve_unwraps_seat_envelope(self, mock_request, _mock_license, _mock_token):- mock_request.return_value = _billing_response({"seat": MOCK_SEAT, "extra": "ignored"})- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code")- assert response.status_code == status.HTTP_200_OK- assert response.json()["id"] == "seat_123"- assert "extra" not in response.json()-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_list_does_not_unwrap(self, mock_request, _mock_license, _mock_token):- payload = {"seats": [MOCK_SEAT]}- mock_request.return_value = _billing_response(payload)- self._auth_as_admin()- response = self.client.get("/api/seats/?product_key=posthog_code")- assert response.status_code == status.HTTP_200_OK- assert "seats" in response.json()-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_error_response_passes_through(self, mock_request, _mock_license, _mock_token):- mock_request.return_value = _billing_response({"error": "seat not found"}, status_code=404, ok=False)- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code")- assert response.status_code == 404- assert response.json()["error"] == "seat not found"-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_204_returns_no_content(self, mock_request, _mock_license, _mock_token):- billing_resp = MagicMock()- billing_resp.status_code = 204- mock_request.return_value = billing_resp- self._auth_as_member()- response = self.client.delete("/api/seats/me/?product_key=posthog_code")- assert response.status_code == status.HTTP_204_NO_CONTENT-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_response_without_seat_key_passes_through(self, mock_request, _mock_license, _mock_token):- payload = {"message": "ok", "some_data": 123}- mock_request.return_value = _billing_response(payload)- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code")- assert response.status_code == status.HTTP_200_OK- assert response.json() == payload---MOCK_FREE_SEAT = {- "id": "seat_free",- "user_distinct_id": "user-abc",- "product_key": "posthog_code",- "plan_key": "posthog-code-free-20260301",- "status": "active",- "end_reason": None,- "created_at": "2026-04-01T00:00:00Z",- "active_until": None,- "active_from": "2026-04-01T00:00:00Z",-}--MOCK_PRO_SEAT = {- "id": "seat_pro",- "user_distinct_id": "user-abc",- "product_key": "posthog_code",- "plan_key": "posthog-code-200-20260301",- "status": "active",- "end_reason": None,- "created_at": "2026-04-01T00:00:00Z",- "active_until": None,- "active_from": "2026-04-01T00:00:00Z",-}--MOCK_PRO_V2_SEAT = {- "id": "seat_pro_v2",- "user_distinct_id": "user-abc",- "product_key": "posthog_code",- "plan_key": "posthog-code-pro-200-20260422",- "status": "active",- "end_reason": None,- "created_at": "2026-04-01T00:00:00Z",- "active_until": None,- "active_from": "2026-04-01T00:00:00Z",-}---@patch("products.tasks.backend.presentation.views.seat_api.get_cached_instance_license", return_value=MagicMock())-class TestSeatAPIBestPlan(BaseSeatAPITest):- """``best=true`` returns the highest-tier seat across all orgs."""-- org2: ClassVar[Organization]-- @classmethod- def setUpTestData(cls):- super().setUpTestData()- cls.org2 = Organization.objects.create(name="Second Org")- cls.org2.members.add(cls.user)-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)- def test_single_org_returns_that_seat(self, _mock_token, mock_request, _mock_license):- mock_request.return_value = _billing_response({"seat": MOCK_FREE_SEAT})- self._auth_as_admin()- response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")- assert response.status_code == status.HTTP_200_OK- assert response.json()["plan_key"] == "posthog-code-free-20260301"- assert response.json()["organization_id"] == str(self.organization.id)- assert response.json()["organization_name"] == "Test Org"-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)- def test_multi_org_returns_pro_over_free(self, _mock_token, mock_request, _mock_license):- mock_request.side_effect = [- _billing_response({"seat": MOCK_FREE_SEAT}),- _billing_response({"seat": MOCK_PRO_SEAT}),- ]- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")- assert response.status_code == status.HTTP_200_OK- assert response.json()["plan_key"] == "posthog-code-200-20260301"- assert "organization_id" in response.json()-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)- def test_multi_org_returns_pro_regardless_of_order(self, _mock_token, mock_request, _mock_license):- mock_request.side_effect = [- _billing_response({"seat": MOCK_PRO_SEAT}),- _billing_response({"seat": MOCK_FREE_SEAT}),- ]- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")- assert response.status_code == status.HTTP_200_OK- assert response.json()["plan_key"] == "posthog-code-200-20260301"-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)- def test_all_billing_failures_returns_503(self, _mock_token, mock_request, _mock_license):- """A failed lookup is not a confirmed absence: the LLM gateway caches a 404- as seat_missing and free-caps the user, so a billing outage must surface- as an error it fails open on, never as 404."""- mock_request.return_value = _billing_response({"error": "fail"}, status_code=500, ok=False)- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")- assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)- def test_partial_failure_with_no_seat_returns_503(self, _mock_token, mock_request, _mock_license):- mock_request.side_effect = [- _billing_response({"error": "fail"}, status_code=500, ok=False),- _billing_response({"error": "No seat found for this user"}, status_code=404, ok=False),- ]- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")- assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)- def test_all_orgs_conclusively_no_seat_returns_404(self, _mock_token, mock_request, _mock_license):- """404 stays 404 when every org's lookup succeeded and found nothing —- the gateway's seat_missing free-cap depends on this conclusive signal."""- mock_request.return_value = _billing_response(- {"error": "No seat found for this user"}, status_code=404, ok=False- )- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")- assert response.status_code == status.HTTP_404_NOT_FOUND-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)- def test_partial_failure_returns_best_available(self, _mock_token, mock_request, _mock_license):- mock_request.side_effect = [- _billing_response({"error": "fail"}, status_code=500, ok=False),- _billing_response({"seat": MOCK_PRO_SEAT}),- ]- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")- assert response.status_code == status.HTTP_200_OK- assert response.json()["plan_key"] == "posthog-code-200-20260301"-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)- def test_best_ignored_for_non_me_pk(self, _mock_token, mock_request, _mock_license):- mock_request.return_value = _billing_response({"seat": MOCK_SEAT})- self._auth_as_admin()- response = self.client.get(f"/api/seats/{self.user.distinct_id}/?product_key=posthog_code&best=true")- assert response.status_code == status.HTTP_200_OK- assert mock_request.call_count == 1-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)- def test_without_best_param_does_single_call(self, _mock_token, mock_request, _mock_license):- mock_request.return_value = _billing_response({"seat": MOCK_SEAT})- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code")- assert response.status_code == status.HTTP_200_OK- assert mock_request.call_count == 1-- @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)- def test_no_orgs_returns_400(self, _mock_token, _mock_license):- self.client.force_authenticate(self.external_user)- response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")- assert response.status_code == status.HTTP_400_BAD_REQUEST-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)- def test_pro_v2_prefix_recognized(self, _mock_token, mock_request, _mock_license):- mock_request.side_effect = [- _billing_response({"seat": MOCK_FREE_SEAT}),- _billing_response({"seat": MOCK_PRO_V2_SEAT}),- ]- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")- assert response.status_code == status.HTTP_200_OK- assert response.json()["plan_key"] == "posthog-code-pro-200-20260422"-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)- def test_no_plan_key_loses_to_free(self, _mock_token, mock_request, _mock_license):- no_plan_seat = {**MOCK_FREE_SEAT, "plan_key": None, "id": "seat_none"}- mock_request.side_effect = [- _billing_response({"seat": no_plan_seat}),- _billing_response({"seat": MOCK_FREE_SEAT}),- ]- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")- assert response.status_code == status.HTTP_200_OK- assert response.json()["plan_key"] == "posthog-code-free-20260301"-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)- def test_active_free_beats_canceled_pro(self, _mock_token, mock_request, _mock_license):- canceled_pro = {**MOCK_PRO_SEAT, "status": "canceled", "id": "seat_canceled_pro"}- mock_request.side_effect = [- _billing_response({"seat": canceled_pro}),- _billing_response({"seat": MOCK_FREE_SEAT}),- ]- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")- assert response.status_code == status.HTTP_200_OK- assert response.json()["plan_key"] == "posthog-code-free-20260301"- assert response.json()["status"] == "active"-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)- def test_canceling_pro_beats_active_free(self, _mock_token, mock_request, _mock_license):- canceling_pro = {- **MOCK_PRO_SEAT,- "status": "canceling",- "id": "seat_canceling_pro",- "active_until": "2026-06-04T00:00:00Z",- }- mock_request.side_effect = [- _billing_response({"seat": canceling_pro}),- _billing_response({"seat": MOCK_FREE_SEAT}),- ]- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")- assert response.status_code == status.HTTP_200_OK- assert response.json()["plan_key"] == MOCK_PRO_SEAT["plan_key"]- assert response.json()["status"] == "canceling"-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)- def test_future_exception_handled_gracefully(self, _mock_token, mock_request, _mock_license):- mock_request.side_effect = [- RuntimeError("connection reset"),- _billing_response({"seat": MOCK_PRO_SEAT}),- ]- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")- assert response.status_code == status.HTTP_200_OK- assert response.json()["plan_key"] == "posthog-code-200-20260301"-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token")- def test_partial_header_failure_returns_available_seat(self, mock_token, mock_request, _mock_license):- mock_token.side_effect = [NotAuthenticated("no member"), MOCK_BILLING_TOKEN]- mock_request.return_value = _billing_response({"seat": MOCK_FREE_SEAT})- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")- assert response.status_code == status.HTTP_200_OK- assert response.json()["plan_key"] == "posthog-code-free-20260301"-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)- def test_same_tier_picks_oldest_seat(self, _mock_token, mock_request, _mock_license):- newer_pro = {**MOCK_PRO_SEAT, "id": "seat_newer", "created_at": "2026-06-01T00:00:00Z"}- older_pro = {**MOCK_PRO_SEAT, "id": "seat_older", "created_at": "2026-03-01T00:00:00Z"}- mock_request.side_effect = [- _billing_response({"seat": newer_pro}),- _billing_response({"seat": older_pro}),- ]- self._auth_as_member()- response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")- assert response.status_code == status.HTTP_200_OK- assert response.json()["id"] == "seat_older"---@patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)-@patch("products.tasks.backend.presentation.views.seat_api.get_cached_instance_license", return_value=MagicMock())-class TestSeatAPIKeyAccess(BaseSeatAPITest):- """Personal API keys are allowed so the LLM gateway can resolve seats."""-- @patch("products.tasks.backend.presentation.views.seat_api.requests.request")- def test_personal_api_key_allowed(self, mock_request, _mock_license, _mock_token):- mock_request.return_value = _billing_response({"seat": MOCK_SEAT})- token = generate_random_token_personal()- PersonalAPIKey.objects.create(- label="test",- user=self.admin_user,- scopes=["*"],- secure_value=hash_key_value(token),- )- self.client.logout()- response = self.client.get(- "/api/seats/me/?product_key=posthog_code",- headers={"authorization": f"Bearer {token}"},- )- assert response.status_code == status.HTTP_200_OK