Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(tasks): add project-scoped desktop access policy (#87066)

Jonathan Mieloob17302863735
diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.py
index 4bd29fd37745..5bc4fde50e5c 100644
--- a/ee/billing/billing_manager.py
+++ b/ee/billing/billing_manager.py
@@ -3,11 +3,12 @@ import json
import time
import hashlib
from datetime import UTC, datetime, timedelta
-from enum import Enum
-from typing import Any, Optional, cast
+from enum import Enum, StrEnum
+from typing import Any, Literal, Optional, cast
from uuid import UUID
from django.conf import settings
+from django.core.cache import cache
from django.db.models import F
from django.utils import timezone
from django.utils.dateparse import parse_datetime
@@ -19,6 +20,7 @@ from requests import JSONDecodeError
from rest_framework.exceptions import NotAuthenticated
from posthog.cloud_utils import get_cached_instance_license
+from posthog.dataclasses import frozen
from posthog.event_usage import report_user_action
from posthog.exceptions_capture import capture_exception
from posthog.models import Organization
@@ -47,6 +49,30 @@ BILLING_TIMESERIES_REQUEST_TIMEOUT = (5, 30)
BILLING_ALERTS_EVALUATION_SERVICE_ACTION = "billing_alerts_evaluation"
+StartupProgramLabel = Literal["Startup", "YC"]
+
+
+class PrepaidCreditState(StrEnum):
+ NONE = "none"
+ PENDING = "pending"
+ ACTIVE = "active"
+ EXHAUSTED = "exhausted"
+ EXPIRED = "expired"
+
+
+class FundingStatusUnavailable(Exception):
+ pass
+
+
+_FUNDING_STATUS_UNAVAILABLE_CACHE_VALUE = "__funding_status_unavailable__"
+
+
+@frozen
+class OrganizationFundingStatus:
+ startup_program_label: StartupProgramLabel | None
+ prepaid_credit_state: PrepaidCreditState
+
+
class BillingAPIErrorCodes(Enum):
OPEN_INVOICES_ERROR = "open_invoices_error"
@@ -200,6 +226,31 @@ def handle_billing_service_error(res: requests.Response, valid_codes=(200, 201,
raise Exception(f"Billing service returned bad status code: {res.status_code}", f"body:", res.text)
+def _parse_funding_status(data: object) -> OrganizationFundingStatus:
+ if not isinstance(data, dict):
+ raise FundingStatusUnavailable("Billing returned an invalid funding status response")
+
+ if "startup_program_label" not in data:
+ raise FundingStatusUnavailable("Billing returned an invalid startup program label")
+ raw_startup_program_label = data.get("startup_program_label")
+ if raw_startup_program_label not in (None, "Startup", "YC"):
+ raise FundingStatusUnavailable("Billing returned an invalid startup program label")
+ startup_program_label = cast(StartupProgramLabel | None, raw_startup_program_label)
+
+ raw_prepaid_credit_state = data.get("prepaid_credit_state")
+ if not isinstance(raw_prepaid_credit_state, str):
+ raise FundingStatusUnavailable("Billing returned an invalid prepaid credit state")
+ try:
+ prepaid_credit_state = PrepaidCreditState(raw_prepaid_credit_state)
+ except ValueError as error:
+ raise FundingStatusUnavailable("Billing returned an invalid prepaid credit state") from error
+
+ return OrganizationFundingStatus(
+ startup_program_label=startup_program_label,
+ prepaid_credit_state=prepaid_credit_state,
+ )
+
+
class BillingManager:
license: License | None
user: User | None
@@ -392,6 +443,44 @@ class BillingManager:
handle_billing_service_error(res)
+ def get_funding_status(self, organization: Organization) -> OrganizationFundingStatus:
+ cache_key = f"organization_funding_status:{organization.id}"
+ try:
+ cached_status = cache.get(cache_key)
+ except Exception:
+ logger.warning("funding_status_cache_read_failed", exc_info=True)
+ cached_status = None
+
+ if cached_status == _FUNDING_STATUS_UNAVAILABLE_CACHE_VALUE:
+ raise FundingStatusUnavailable("Could not resolve organization funding status")
+ if cached_status is not None:
+ return _parse_funding_status(cached_status)
+
+ try:
+ response = requests.get(
+ f"{BILLING_SERVICE_URL}/api/billing/funding-status/",
+ headers=self.get_auth_headers(organization),
+ timeout=5,
+ )
+ handle_billing_service_error(response, valid_codes=(200,))
+ raw_status = response.json()
+ funding_status = _parse_funding_status(raw_status)
+ except Exception as error:
+ try:
+ cache.set(cache_key, _FUNDING_STATUS_UNAVAILABLE_CACHE_VALUE, timeout=5)
+ except Exception:
+ logger.warning("funding_status_failure_cache_write_failed", exc_info=True)
+ if isinstance(error, FundingStatusUnavailable):
+ raise
+ raise FundingStatusUnavailable("Could not resolve organization funding status") from error
+
+ try:
+ cache.set(cache_key, raw_status, timeout=30)
+ except Exception:
+ logger.warning("funding_status_cache_write_failed", exc_info=True)
+
+ return funding_status
+
def _get_default_billing_response(self, organization: Organization | None) -> dict[str, Any]:
products = self.get_default_products(organization)
response = {
diff --git a/ee/billing/test/test_billing_manager.py b/ee/billing/test/test_billing_manager.py
index 3454616d9b7c..a026b839de8f 100644
--- a/ee/billing/test/test_billing_manager.py
+++ b/ee/billing/test/test_billing_manager.py
@@ -27,7 +27,11 @@ from ee.billing.billing_manager import (
BILLING_PROVIDER_WEBHOOK_SIGNATURE_VERSION,
BILLING_PROVIDER_WEBHOOK_TIMESTAMP_HEADER,
BillingManager,
+ FundingStatusUnavailable,
+ OrganizationFundingStatus,
+ PrepaidCreditState,
_get_user_organization_role,
+ _parse_funding_status,
build_billing_token,
)
from ee.billing.billing_types import BillingProvider, BillingStatus, Product
@@ -59,6 +63,60 @@ def create_default_products_response(**kwargs) -> dict[str, list[Product]]:
return data
+class TestFundingStatusParsing(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "normal",
+ {"startup_program_label": None, "prepaid_credit_state": "none"},
+ OrganizationFundingStatus(
+ startup_program_label=None,
+ prepaid_credit_state=PrepaidCreditState.NONE,
+ ),
+ ),
+ (
+ "startup_active",
+ {"startup_program_label": "Startup", "prepaid_credit_state": "active"},
+ OrganizationFundingStatus(
+ startup_program_label="Startup",
+ prepaid_credit_state=PrepaidCreditState.ACTIVE,
+ ),
+ ),
+ (
+ "yc_expired",
+ {"startup_program_label": "YC", "prepaid_credit_state": "expired"},
+ OrganizationFundingStatus(
+ startup_program_label="YC",
+ prepaid_credit_state=PrepaidCreditState.EXPIRED,
+ ),
+ ),
+ ]
+ )
+ def test_parses_funding_status(
+ self, _name: str, payload: dict[str, str | None], expected: OrganizationFundingStatus
+ ) -> None:
+ self.assertEqual(_parse_funding_status(payload), expected)
+
+ @parameterized.expand(
+ [
+ ("not_an_object", []),
+ (
+ "invalid_program_label",
+ {"startup_program_label": "Growth", "prepaid_credit_state": "none"},
+ ),
+ ("missing_program_label", {"prepaid_credit_state": "none"}),
+ ("missing_credit_state", {"startup_program_label": None}),
+ (
+ "invalid_credit_state",
+ {"startup_program_label": None, "prepaid_credit_state": "paid"},
+ ),
+ ]
+ )
+ def test_rejects_invalid_funding_status(self, _name: str, payload: object) -> None:
+ with self.assertRaises(FundingStatusUnavailable):
+ _parse_funding_status(payload)
+
+
class TestBillingManager(BaseTest):
@patch(
"ee.billing.billing_manager.requests.get",
@@ -130,6 +188,80 @@ class TestBillingManager(BaseTest):
if expect_header:
assert headers["X-PostHog-Actor-IP"] == ip_address
+ @patch("ee.billing.billing_manager.BILLING_SERVICE_URL", "https://billing.posthog.com")
+ @patch("ee.billing.billing_manager.cache")
+ @patch("ee.billing.billing_manager.requests.get")
+ def test_get_funding_status_uses_organization_scoped_billing_token(
+ self, mock_get: MagicMock, mock_cache: MagicMock
+ ) -> None:
+ license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
+ key="key123::key123",
+ plan="enterprise",
+ valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
+ )
+ payload = {"startup_program_label": None, "prepaid_credit_state": "none"}
+ mock_cache.get.return_value = None
+ mock_get.return_value = MagicMock(status_code=200, json=MagicMock(return_value=payload))
+
+ result = BillingManager(license, self.user).get_funding_status(self.organization)
+
+ assert result == OrganizationFundingStatus(
+ startup_program_label=None,
+ prepaid_credit_state=PrepaidCreditState.NONE,
+ )
+ mock_get.assert_called_once()
+ call = mock_get.call_args
+ assert call.args[0] == "https://billing.posthog.com/api/billing/funding-status/"
+ assert call.kwargs["headers"]["Authorization"].startswith("Bearer ")
+ assert call.kwargs["timeout"] == 5
+ mock_cache.set.assert_called_once_with(
+ f"organization_funding_status:{self.organization.id}", payload, timeout=30
+ )
+
+ @patch("ee.billing.billing_manager.cache")
+ @patch("ee.billing.billing_manager.requests.get")
+ def test_get_funding_status_uses_cached_value(self, mock_get: MagicMock, mock_cache: MagicMock) -> None:
+ mock_cache.get.return_value = {"startup_program_label": "YC", "prepaid_credit_state": "expired"}
+
+ result = BillingManager(MagicMock(), self.user).get_funding_status(self.organization)
+
+ assert result == OrganizationFundingStatus(
+ startup_program_label="YC",
+ prepaid_credit_state=PrepaidCreditState.EXPIRED,
+ )
+ mock_get.assert_not_called()
+
+ @patch("ee.billing.billing_manager.cache")
+ @patch("ee.billing.billing_manager.requests.get")
+ def test_get_funding_status_ignores_cache_failure(self, mock_get: MagicMock, mock_cache: MagicMock) -> None:
+ payload = {"startup_program_label": None, "prepaid_credit_state": "active"}
+ mock_cache.get.side_effect = RuntimeError("cache unavailable")
+ mock_cache.set.side_effect = RuntimeError("cache unavailable")
+ mock_get.return_value = MagicMock(status_code=200, json=MagicMock(return_value=payload))
+
+ manager = BillingManager(MagicMock(), self.user)
+ with patch.object(manager, "get_auth_headers", return_value={}):
+ result = manager.get_funding_status(self.organization)
+
+ assert result.prepaid_credit_state == PrepaidCreditState.ACTIVE
+
+ @patch("ee.billing.billing_manager.cache")
+ @patch("ee.billing.billing_manager.requests.get", side_effect=requests.Timeout)
+ def test_get_funding_status_caches_billing_failure(self, mock_get: MagicMock, mock_cache: MagicMock) -> None:
+ cached_values: list[object | None] = [None]
+ mock_cache.get.side_effect = lambda _key: cached_values[-1]
+ mock_cache.set.side_effect = lambda _key, value, timeout: cached_values.append(value)
+
+ manager = BillingManager(MagicMock(), self.user)
+ with patch.object(manager, "get_auth_headers", return_value={}):
+ with self.assertRaises(FundingStatusUnavailable):
+ manager.get_funding_status(self.organization)
+ with self.assertRaises(FundingStatusUnavailable):
+ manager.get_funding_status(self.organization)
+
+ mock_get.assert_called_once()
+ assert mock_cache.set.call_args.kwargs["timeout"] == 5
+
@patch(
"ee.billing.billing_manager.requests.patch",
return_value=MagicMock(status_code=200, json=MagicMock(return_value={"text": "ok"})),
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 8d3e4647e97c..7ce1332b70a8 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -689,6 +689,7 @@ SPECTACULAR_SETTINGS = {
# --- Inline value lists (type-hint enums, no x-spec-enum-id) ---
"TileSpacingEnum": ["tight", "condensed", "standard", "relaxed", "wide"],
"LayoutCompactionEnum": ["vertical", "horizontal", "stable"],
+ "DesktopAccessReasonEnum": "products.tasks.backend.facade.contracts.DESKTOP_ACCESS_REASON_SCHEMA_VALUES",
"PropertyGroupOperator": ["AND", "OR"],
# `scope`/`state` are generic field names; one shared name for the canvas state scope set.
"CanvasStateScopeEnum": ["user", "shared"],
diff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.py
index 9e079b722656..ca25fd8e495c 100644
--- a/products/slack_app/backend/services/slack_messages.py
+++ b/products/slack_app/backend/services/slack_messages.py
@@ -660,16 +660,6 @@ def _public_url(path: str) -> str:
return absolute_uri(path)
-def workspace_org_ids(slack_team_id: str) -> set:
- """Organizations connected to this Slack workspace — the scope a Slack identity may
- resolve a PostHog user within."""
- return set(
- Integration.objects.filter(kind="slack", integration_id=slack_team_id).values_list(
- "team__organization_id", flat=True
- )
- )
-
-
def viewer_has_code_access(integration: Integration, slack_user_id: str | None) -> bool:
"""Whether the Slack identity reading this can open a PostHog Code link.
@@ -678,7 +668,7 @@ def viewer_has_code_access(integration: Integration, slack_user_id: str | None)
flag-service error means no link rather than one that dead-ends.
"""
from products.slack_app.backend.services.slack_user_oauth import find_linked_posthog_user # noqa: PLC0415
- from products.tasks.backend.facade.access import has_tasks_access # noqa: PLC0415
+ from products.tasks.backend.facade.access import get_desktop_access_decision # noqa: PLC0415
if not slack_user_id:
return False
@@ -686,9 +676,11 @@ def viewer_has_code_access(integration: Integration, slack_user_id: str | None)
user = find_linked_posthog_user(
slack_user_id=slack_user_id,
slack_team_id=integration.integration_id,
- candidate_org_ids=workspace_org_ids(integration.integration_id),
+ candidate_org_ids={integration.team.organization_id},
)
- return user is not None and has_tasks_access(user)
+ if user is None:
+ return False
+ return get_desktop_access_decision(user, integration.team.organization).allowed
except Exception:
logger.exception("slack_app_viewer_code_access_check_failed", integration_id=integration.id)
return False
diff --git a/products/slack_app/backend/tests/services/slack_messages/test_run_footer.py b/products/slack_app/backend/tests/services/slack_messages/test_run_footer.py
index 25b30d1e2726..fab1b1f770f3 100644
--- a/products/slack_app/backend/tests/services/slack_messages/test_run_footer.py
+++ b/products/slack_app/backend/tests/services/slack_messages/test_run_footer.py
@@ -1,4 +1,5 @@
from types import SimpleNamespace
+from typing import cast
from uuid import uuid4
from unittest.mock import patch
@@ -82,33 +83,43 @@ class TestLoadRunFooter(SimpleTestCase):
class TestViewerHasCodeAccess(SimpleTestCase):
def _integration(self) -> Integration:
- return Integration(config={}, integration_id="T1")
+ organization = SimpleNamespace(id="org-1")
+ team = SimpleNamespace(organization=organization, organization_id=organization.id)
+ return cast(Integration, SimpleNamespace(config={}, integration_id="T1", id=1, team=team))
- @patch("products.tasks.backend.facade.access.has_tasks_access")
+ @patch("products.tasks.backend.facade.access.get_desktop_access_decision")
def test_no_slack_identity_means_no_access_without_consulting_the_flag(self, mock_has_access) -> None:
assert viewer_has_code_access(self._integration(), None) is False
mock_has_access.assert_not_called()
- @patch("products.slack_app.backend.services.slack_messages.workspace_org_ids", return_value=set())
@patch("products.slack_app.backend.services.slack_user_oauth.find_linked_posthog_user", return_value=None)
- @patch("products.tasks.backend.facade.access.has_tasks_access")
- def test_an_unlinked_slack_identity_means_no_access(self, mock_has_access, _mock_find, _mock_orgs) -> None:
+ @patch("products.tasks.backend.facade.access.get_desktop_access_decision")
+ def test_an_unlinked_slack_identity_means_no_access(self, mock_has_access, _mock_find) -> None:
assert viewer_has_code_access(self._integration(), "U1") is False
mock_has_access.assert_not_called()
@parameterized.expand([("granted", True, True), ("denied", False, False)])
- @patch("products.slack_app.backend.services.slack_messages.workspace_org_ids", return_value=set())
@patch("products.slack_app.backend.services.slack_user_oauth.find_linked_posthog_user")
- @patch("products.tasks.backend.facade.access.has_tasks_access")
+ @patch("products.tasks.backend.facade.access.get_desktop_access_decision")
def test_a_linked_identity_follows_its_own_code_access(
- self, _name: str, granted: bool, expected: bool, mock_has_access, mock_find, _mock_orgs
+ self, _name: str, granted: bool, expected: bool, mock_has_access, mock_find
) -> None:
# The reader, not the task creator: a thread outlives whoever opened it.
mock_find.return_value = object()
- mock_has_access.return_value = granted
+ mock_has_access.return_value = SimpleNamespace(allowed=granted)
- assert viewer_has_code_access(self._integration(), "U1") is expected
+ integration = self._integration()
- @patch("products.slack_app.backend.services.slack_messages.workspace_org_ids", side_effect=RuntimeError("db down"))
- def test_a_lookup_failure_withholds_the_links_rather_than_guessing(self, _mock_orgs) -> None:
+ assert viewer_has_code_access(integration, "U1") is expected
+ mock_find.assert_called_once_with(
+ slack_user_id="U1",
+ slack_team_id="T1",
+ candidate_org_ids={integration.team.organization_id},
+ )
+
+ @patch(
+ "products.slack_app.backend.services.slack_user_oauth.find_linked_posthog_user",
+ side_effect=RuntimeError("db down"),
+ )
+ def test_a_lookup_failure_withholds_the_links_rather_than_guessing(self, _mock_find) -> None:
assert viewer_has_code_access(self._integration(), "U1") is False
diff --git a/products/tasks/backend/access.py b/products/tasks/backend/access.py
index 3d054a3ff0c9..75e529b1fb5e 100644
--- a/products/tasks/backend/access.py
+++ b/products/tasks/backend/access.py
@@ -1,48 +1,150 @@
+from enum import StrEnum
from typing import TYPE_CHECKING
-import posthoganalytics
-
+from posthog.cloud_utils import get_cached_instance_license
from posthog.models.user import User
+from posthog.ph_client import feature_enabled_or_false, get_feature_flag_or_none
+
+from products.tasks.backend.facade.contracts import DesktopAccessReason
+from products.tasks.backend.metrics import observe_desktop_access_decision
+from products.tasks.backend.models import CodeInviteRedemption
-from .models import CodeInviteRedemption
+from ee.billing.billing_manager import (
+ BillingManager,
+ FundingStatusUnavailable,
+ OrganizationFundingStatus,
+ PrepaidCreditState,
+)
if TYPE_CHECKING:
+ from posthog.models.organization import Organization
from posthog.models.team.team import Team
+DESKTOP_ACCESS_GATE_FLAG = "posthog-desktop-access-gate"
+DESKTOP_ACCESS_OVERRIDE_FLAG = "posthog-desktop-access-override"
+
+
+class DesktopAccessResolutionError(Exception):
+ pass
-def _is_flag_enabled(flag_key: str, user: User, team: "Team | None" = None) -> bool:
- if not user.distinct_id:
- return False
- org = team.organization if team is not None else getattr(user, "organization", None)
- kwargs: dict = {
- "only_evaluate_locally": False,
- "send_feature_flag_events": False,
- }
- if org is not None:
- # The `tasks` flag's release conditions are mostly person-level (email allowlist + domain),
- # but maybe we want org level conditions later on.
- org_id = str(org.id)
- kwargs["groups"] = {"organization": org_id}
- kwargs["group_properties"] = {"organization": {"id": org_id}}
- return bool(posthoganalytics.feature_enabled(flag_key, user.distinct_id, **kwargs))
+
+class DesktopAccessDecision(StrEnum):
+ ALLOWED = "allowed"
+ LEGACY_ACCESS_REQUIRED = "legacy_access_required"
+ STARTUP_PLAN = "startup_plan"
+ PREPAID_CREDITS = "prepaid_credits"
+
+ @property
+ def allowed(self) -> bool:
+ return self == self.ALLOWED
+
+ @property
+ def reason(self) -> DesktopAccessReason | None:
+ if self == self.STARTUP_PLAN:
+ return DesktopAccessReason.STARTUP_PLAN
+ if self == self.PREPAID_CREDITS:
+ return DesktopAccessReason.PREPAID_CREDITS
+ return None
def has_tasks_access(user: User) -> bool:
- """
- User has access to PostHog Desktop if the `tasks` feature flag is enabled for them
- OR they have redeemed an invite code.
- """
- if not user or not user.is_authenticated:
+ if not user or not user.is_authenticated or not user.distinct_id:
return False
- if _is_flag_enabled("tasks", user):
+
+ organization = getattr(user, "organization", None)
+ organization_id = str(organization.id) if organization is not None else None
+ if feature_enabled_or_false(
+ "tasks",
+ str(user.distinct_id),
+ groups={"organization": organization_id} if organization_id is not None else None,
+ group_properties={"organization": {"id": organization_id}} if organization_id is not None else None,
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ ):
return True
return CodeInviteRedemption.objects.filter(user=user).exists()
+def _get_funding_status(user: User, organization: "Organization") -> OrganizationFundingStatus:
+ try:
+ return BillingManager(get_cached_instance_license(), user).get_funding_status(organization)
+ except FundingStatusUnavailable as error:
+ raise DesktopAccessResolutionError("Could not resolve organization funding status") from error
+
+
+def get_desktop_access_decision(user: User, organization: "Organization") -> DesktopAccessDecision:
+ if not user or not user.is_authenticated or not user.distinct_id:
+ raise DesktopAccessResolutionError("Authentication is required to evaluate Desktop access")
+
+ organization_id = str(organization.id)
+ groups = {"organization": organization_id}
+ group_properties = {"organization": {"id": organization_id}}
+ rollout_enabled = get_feature_flag_or_none(
+ DESKTOP_ACCESS_GATE_FLAG,
+ str(user.distinct_id),
+ groups=groups,
+ group_properties=group_properties,
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ if not isinstance(rollout_enabled, bool):
+ observe_desktop_access_decision(outcome="resolution_failure")
+ raise DesktopAccessResolutionError("Could not evaluate the Desktop access rollout")
+ if not rollout_enabled:
+ try:
+ legacy_access_allowed = has_tasks_access(user)
+ except Exception as error:
+ observe_desktop_access_decision(outcome="resolution_failure")
+ raise DesktopAccessResolutionError("Could not evaluate legacy Desktop access") from error
+ if legacy_access_allowed:
+ observe_desktop_access_decision(outcome="legacy_allowed")
+ return DesktopAccessDecision.ALLOWED
+ observe_desktop_access_decision(outcome="legacy_denied")
+ return DesktopAccessDecision.LEGACY_ACCESS_REQUIRED
+
+ override_enabled = get_feature_flag_or_none(
+ DESKTOP_ACCESS_OVERRIDE_FLAG,
+ str(user.distinct_id),
+ groups=groups,
+ group_properties=group_properties,
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ if not isinstance(override_enabled, bool):
+ observe_desktop_access_decision(outcome="resolution_failure")
+ raise DesktopAccessResolutionError("Could not evaluate the Desktop access override")
+ if override_enabled:
+ observe_desktop_access_decision(outcome="override")
+ return DesktopAccessDecision.ALLOWED
+
+ try:
+ funding_status = _get_funding_status(user, organization)
+ except DesktopAccessResolutionError:
+ observe_desktop_access_decision(outcome="resolution_failure")
+ raise
+
+ if funding_status.startup_program_label is not None:
+ observe_desktop_access_decision(outcome="startup_plan")
+ return DesktopAccessDecision.STARTUP_PLAN
+ if funding_status.prepaid_credit_state in {PrepaidCreditState.PENDING, PrepaidCreditState.ACTIVE}:
+ observe_desktop_access_decision(outcome="prepaid_credits")
+ return DesktopAccessDecision.PREPAID_CREDITS
+
+ observe_desktop_access_decision(outcome="allowed")
+ return DesktopAccessDecision.ALLOWED
+
+
def has_loops_access(user: User, team: "Team | None" = None) -> bool:
- """Loops sits behind its own `loops` flag (see docs/LOOPS.md Rollout).
+ if not user.distinct_id:
+ return False
- Independent of `has_tasks_access`: `tasks` gates the Desktop waitlist that user-triggered cloud
- runs require (see code_access_required_response), while Loops gates on its own flag instead.
- """
- return _is_flag_enabled("loops", user, team)
+ organization = team.organization if team is not None else getattr(user, "organization", None)
+ organization_id = str(organization.id) if organization is not None else None
+ return feature_enabled_or_false(
+ "loops",
+ str(user.distinct_id),
+ groups={"organization": organization_id} if organization_id is not None else None,
+ group_properties={"organization": {"id": organization_id}} if organization_id is not None else None,
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
diff --git a/products/tasks/backend/facade/access.py b/products/tasks/backend/facade/access.py
index 1db19bff6be1..b4096f2013f0 100644
--- a/products/tasks/backend/facade/access.py
+++ b/products/tasks/backend/facade/access.py
@@ -1,15 +1,11 @@
-"""
-Facade re-exports for tasks access / usage gating.
-
-``has_tasks_access`` reports Desktop waitlist access (the `tasks` flag or a redeemed invite).
-``has_loops_access`` gates Loops on its own `loops` flag (see docs/LOOPS.md Rollout).
-``code_access_required_response`` provides the HTTP-layer 403 that gates user-triggered cloud
-execution on Desktop access; ``usage_limit_response`` provides the HTTP-layer 429 that meters
-cloud execution paths. Presentation imports them from here rather than reaching the internal
-``access`` / ``logic.services.code_usage_gate`` modules directly.
-"""
-
-from products.tasks.backend.access import has_loops_access, has_tasks_access
+from products.tasks.backend.access import (
+ DesktopAccessDecision,
+ DesktopAccessResolutionError,
+ get_desktop_access_decision,
+ has_loops_access,
+ has_tasks_access,
+)
+from products.tasks.backend.facade.contracts import DesktopAccessReason
from products.tasks.backend.logic.services.code_usage_gate import (
code_access_required_response,
compute_quota_limit_response,
@@ -17,8 +13,12 @@ from products.tasks.backend.logic.services.code_usage_gate import (
)
__all__ = [
+ "DesktopAccessDecision",
+ "DesktopAccessReason",
+ "DesktopAccessResolutionError",
"code_access_required_response",
"compute_quota_limit_response",
+ "get_desktop_access_decision",
"has_loops_access",
"has_tasks_access",
"usage_limit_response",
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index 35f87865ec56..8365dc1faf5a 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -16,6 +16,7 @@ their data results.
"""
from datetime import datetime
+from enum import StrEnum
from typing import Literal
from uuid import UUID
@@ -23,6 +24,14 @@ from pydantic import Field
from pydantic.dataclasses import dataclass
+class DesktopAccessReason(StrEnum):
+ STARTUP_PLAN = "startup_plan"
+ PREPAID_CREDITS = "prepaid_credits"
+
+
+DESKTOP_ACCESS_REASON_SCHEMA_VALUES = [*(reason.value for reason in DesktopAccessReason), None]
+
+
@dataclass(frozen=True)
class TaskDTO:
"""A code task."""
diff --git a/products/tasks/backend/logic/services/code_usage_gate.py b/products/tasks/backend/logic/services/code_usage_gate.py
index 94997b46ee3f..755ecf4bb34b 100644
--- a/products/tasks/backend/logic/services/code_usage_gate.py
+++ b/products/tasks/backend/logic/services/code_usage_gate.py
@@ -1,21 +1,26 @@
import logging
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, cast
+from uuid import UUID
from django.conf import settings
import requests
from rest_framework import status
+from rest_framework.request import Request
from rest_framework.response import Response
+from posthog.auth import OAuthAccessTokenAuthentication
from posthog.models import OAuthAccessToken
+from posthog.permissions import get_authenticator_scopes
if TYPE_CHECKING:
- from posthog.models import User
-from posthog.temporal.oauth import create_oauth_access_token_for_user
+ from posthog.models import Organization, User
+from posthog.temporal.oauth import SANDBOX_OAUTH_APP_CLIENT_IDS, create_oauth_access_token_for_user
from posthog.utils import get_instance_region
-from products.tasks.backend.access import has_tasks_access
+from products.tasks.backend.access import DesktopAccessResolutionError, get_desktop_access_decision
+from products.tasks.backend.facade.contracts import DesktopAccessReason
from products.tasks.backend.logic.services.compute_quota import (
COMPUTE_QUOTA_DENIAL_CODE,
ORGANIZATION_DEACTIVATED_DENIAL_CODE,
@@ -168,25 +173,82 @@ def compute_quota_limit_response(reason: str = COMPUTE_QUOTA_DENIAL_CODE) -> Res
)
-def code_access_required_response(user: "User") -> Response | None:
- """Return a 403 when the user lacks PostHog Desktop access, else None.
+def _task_bound_internal_run(request: Request, task_id: str | UUID | None) -> bool:
+ authenticator = getattr(request, "successful_authenticator", None)
+ authenticator_scopes = get_authenticator_scopes(authenticator) or []
+ if "internal_run:read" not in authenticator_scopes or task_id is None:
+ return False
+ if not isinstance(authenticator, OAuthAccessTokenAuthentication):
+ return False
- The entitlement gate for user-triggered cloud execution: usage-based billing alone
- doesn't control cost for credit-funded teams (startup-program credits cover the meter),
- so cloud runs additionally require the Desktop waitlist (the `tasks` flag or a redeemed
- invite). Endpoints serving generally-available Inbox surfaces skip this for tasks whose
- Inbox entitlement is server-verifiable — see ``task_exempt_from_code_access``.
- """
- if has_tasks_access(user):
+ access_token = authenticator.access_token
+ application = access_token.application
+ if application is None or application.client_id not in SANDBOX_OAUTH_APP_CLIENT_IDS:
+ return False
+
+ try:
+ parsed_task_id = UUID(str(task_id))
+ except ValueError:
+ return False
+ return access_token.sandbox_task_id == parsed_task_id
+
+
+def code_access_required_response(
+ request: Request,
+ organization: "Organization",
+ *,
+ task_id: str | UUID | None = None,
+ fail_open_on_resolution_error: bool = False,
+) -> Response | None:
+ if _task_bound_internal_run(request, task_id):
return None
+
+ try:
+ decision = get_desktop_access_decision(cast("User", request.user), organization)
+ except DesktopAccessResolutionError:
+ logger.warning(
+ "desktop_access_resolution_failed",
+ extra={"organization_id": organization.id, "fail_open": fail_open_on_resolution_error},
+ )
+ if fail_open_on_resolution_error:
+ return None
+ return Response(
+ TaskRunErrorResponseSerializer(
+ {
+ "type": "service_unavailable",
+ "code": "desktop_access_unavailable",
+ "error": "We couldn't verify PostHog Desktop access. Try again.",
+ }
+ ).data,
+ status=status.HTTP_503_SERVICE_UNAVAILABLE,
+ )
+
+ if decision.allowed:
+ return None
+
+ messages = {
+ DesktopAccessReason.STARTUP_PLAN: (
+ "PostHog Desktop isn't available for Startup or YC program organizations. "
+ "Select another organization to continue."
+ ),
+ DesktopAccessReason.PREPAID_CREDITS: (
+ "PostHog Desktop isn't available while this organization has prepaid credits. "
+ "Select another organization to continue."
+ ),
+ }
+ reason = decision.reason
+ error_message = (
+ messages[reason] if reason is not None else "PostHog Desktop access is required to run tasks in the cloud."
+ )
+ payload: dict[str, Any] = {
+ "type": "permission_denied",
+ "code": "code_access_required",
+ "error": error_message,
+ }
+ if reason is not None:
+ payload["reason"] = reason.value
return Response(
- TaskRunErrorResponseSerializer(
- {
- "type": "permission_denied",
- "code": "code_access_required",
- "error": "PostHog Desktop access is required to run tasks in the cloud.",
- }
- ).data,
+ TaskRunErrorResponseSerializer(payload).data,
status=status.HTTP_403_FORBIDDEN,
)
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index 6fe0f7800eb2..83ba65e26caa 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -289,6 +289,15 @@ LOOP_AUTO_PAUSED_TOTAL = Counter(
CodeUsageGateOutcome = Literal["checked_allowed", "checked_blocked", "fail_open", "org_deactivated"]
ComputeQuotaOutcome = Literal["checked_allowed", "checked_blocked", "fail_open"]
+DesktopAccessOutcome = Literal[
+ "allowed",
+ "legacy_allowed",
+ "legacy_denied",
+ "startup_plan",
+ "prepaid_credits",
+ "override",
+ "resolution_failure",
+]
# outcome: checked_allowed/checked_blocked when the LLM gateway answered the usage check,
# fail_open when a gateway/token error let the run proceed unchecked (see LOOPS.md Security:
@@ -306,6 +315,12 @@ COMPUTE_QUOTA_CHECK_TOTAL = Counter(
labelnames=["outcome"],
)
+DESKTOP_ACCESS_DECISIONS_TOTAL = Counter(
+ "posthog_tasks_desktop_access_decisions_total",
+ "PostHog Desktop access decisions by bounded outcome",
+ labelnames=["outcome"],
+)
+
def observe_compute_quota_check(outcome: ComputeQuotaOutcome) -> None:
COMPUTE_QUOTA_CHECK_TOTAL.labels(outcome=outcome).inc()
@@ -604,3 +619,7 @@ def observe_loop_auto_paused() -> None:
def observe_code_usage_gate_check(*, outcome: CodeUsageGateOutcome) -> None:
CODE_USAGE_GATE_CHECK_TOTAL.labels(outcome=outcome).inc()
+
+
+def observe_desktop_access_decision(*, outcome: DesktopAccessOutcome) -> None:
+ DESKTOP_ACCESS_DECISIONS_TOTAL.labels(outcome=outcome).inc()
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 82122d6b04df..0b170b236603 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -1039,7 +1039,7 @@ class Task(DeletedMetaFields, models.Model):
title: str,
description: str,
origin_product: "Task.OriginProduct",
- user_id: int, # Will be used to validate the tasks feature flag and create a personal api key for interacting with PostHog.
+ user_id: int,
repository: str | None = None, # Format: "organization/repository", e.g. "posthog/posthog-js"
channel: Channel | None = None,
create_pr: bool = True,
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 0c8d9759b414..eee48cb68569 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -26,6 +26,7 @@ from products.tasks.backend.facade.contracts import (
ChannelDTO,
ChannelFeedMessageDTO,
ChannelInstructionsDTO,
+ DesktopAccessReason,
SandboxCustomImageDTO,
SandboxEnvironmentDTO,
SlackThreadReferenceDTO,
@@ -908,11 +909,33 @@ class TaskRunSetOutputRequestSerializer(serializers.Serializer):
)
+DESKTOP_ACCESS_REASON_CHOICES = [reason.value for reason in DesktopAccessReason]
+
+
+class DesktopAccessResponseSerializer(serializers.Serializer):
+ allowed = serializers.BooleanField(help_text="Whether the selected project can use PostHog Desktop.")
+ reason = serializers.ChoiceField(
+ choices=DESKTOP_ACCESS_REASON_CHOICES,
+ allow_null=True,
+ help_text="Why Desktop access is blocked, or null when access is allowed.",
+ )
+
+
+class LegacyDesktopAccessResponseSerializer(serializers.Serializer):
+ has_access = serializers.BooleanField(help_text="Whether the user has legacy PostHog Desktop access.")
+ has_loops_access = serializers.BooleanField(help_text="Whether the independent Loops feature is enabled.")
+
+
class TaskRunErrorResponseSerializer(serializers.Serializer):
detail = serializers.CharField(required=False, help_text="Human-readable validation error")
error = serializers.CharField(required=False, help_text="Human-readable error message")
type = serializers.CharField(required=False, help_text="Machine-readable error type")
code = serializers.CharField(required=False, help_text="Machine-readable error code")
+ reason = serializers.ChoiceField(
+ choices=DESKTOP_ACCESS_REASON_CHOICES,
+ required=False,
+ help_text="Why PostHog Desktop access was denied, when applicable.",
+ )
attr = serializers.CharField(required=False, help_text="Request field associated with the error")
missing_artifact_ids = serializers.ListField(
child=serializers.CharField(),
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 87f51729a49f..809f713db5dc 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -99,6 +99,7 @@ from products.tasks.backend.facade.streams import (
from products.tasks.backend.presentation.serializers import (
CodeInviteRedeemRequestSerializer,
ConnectionTokenResponseSerializer,
+ LegacyDesktopAccessResponseSerializer,
ModelCatalogueResponseSerializer,
PinnedTaskIdsResponseSerializer,
RepositoryReadinessQuerySerializer,
@@ -561,6 +562,7 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
def create(self, request, **kwargs):
serializer = self._write_serializer(request.data, serializer_class=TaskCreateSerializer)
+
# Read before create_task, which pops the relationship out of the dict it's handed.
relationship = serializer.validated_data.get("signal_report_task_relationship")
from products.signals.backend.facade.api import ( # noqa: PLC0415 — keeps the signals stack off this module's import path
@@ -996,6 +998,10 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
description="PostHog Desktop access is required, or Pi cloud runtime is disabled",
),
404: OpenApiResponse(description="Task not found"),
+ 503: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer,
+ description="PostHog Desktop access could not be verified",
+ ),
429: OpenApiResponse(
response=TaskRunErrorResponseSerializer,
description=(
@@ -1021,10 +1027,10 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return _pi_cloud_runtime_disabled_response()
# The generally-available Inbox runs tasks through this endpoint too (report "Create PR" /
- # "Discuss", scout chat), so the Desktop waitlist gate applies only to tasks whose Inbox
- # entitlement the server can't verify — see task_exempt_from_code_access.
+ # "Discuss", scout chat), so the Desktop policy applies only to tasks whose Inbox
+ # entitlement the server can't verify. See task_exempt_from_code_access.
if not tasks_facade.task_exempt_from_code_access(pk, self.team_id) and (
- access_response := code_access_required_response(request.user)
+ access_response := code_access_required_response(request, self.organization, task_id=pk)
):
return access_response
if limit_response := usage_limit_response(request.user, self.team_id):
@@ -1079,6 +1085,10 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
429: OpenApiResponse(
response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"
),
+ 503: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer,
+ description="PostHog Desktop access could not be verified",
+ ),
},
summary="Warm a task sandbox",
description=(
@@ -1097,7 +1107,7 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return Response(status=status.HTTP_200_OK)
# Warming is a Desktop-composer feature with no Inbox caller, so no exemption applies.
- if access_response := code_access_required_response(request.user):
+ if access_response := code_access_required_response(request, self.organization):
return access_response
user_id = self._user_id()
@@ -1348,6 +1358,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
429: OpenApiResponse(
response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"
),
+ 503: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer,
+ description="PostHog Desktop access could not be verified",
+ ),
},
summary="Create task run",
description="Create a new run for a specific task without starting execution.",
@@ -1364,7 +1378,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
) == tasks_facade.TaskRuntime.PI and not tasks_facade.pi_cloud_runtime_enabled(self.team, request.user):
return _pi_cloud_runtime_disabled_response()
if not tasks_facade.task_exempt_from_code_access(task_id, self.team_id) and (
- access_response := code_access_required_response(request.user)
+ access_response := code_access_required_response(request, self.organization, task_id=task_id)
):
return access_response
if limit_response := usage_limit_response(request.user, self.team_id):
@@ -1392,6 +1406,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
429: OpenApiResponse(
response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"
),
+ 503: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer,
+ description="PostHog Desktop access could not be verified",
+ ),
},
summary="Start task run",
description="Start an existing cloud run after any initial run-scoped attachments have been uploaded.",
@@ -1426,7 +1444,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# Backstop: don't launch the cloud workflow without Desktop access or for an over-limit team.
if not tasks_facade.task_exempt_from_code_access(task_id, self.team_id) and (
- access_response := code_access_required_response(request.user)
+ access_response := code_access_required_response(request, self.organization, task_id=task_id)
):
return access_response
if limit_response := usage_limit_response(request.user, self.team_id):
@@ -2380,6 +2398,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
response=TaskRunErrorResponseSerializer, description="PostHog Desktop access is required"
),
404: OpenApiResponse(description="Task run not found"),
+ 503: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer,
+ description="PostHog Desktop access could not be verified",
+ ),
429: OpenApiResponse(
response=TaskRunErrorResponseSerializer,
description="Organization reached its PostHog Desktop usage limit",
@@ -2397,7 +2419,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
def connection_token(self, request, pk=None, **kwargs):
task_id = self._ensure_task_accessible()
if not tasks_facade.task_exempt_from_code_access(task_id, self.team_id) and (
- access_response := code_access_required_response(request.user)
+ access_response := code_access_required_response(request, self.organization, task_id=task_id)
):
return access_response
if limit_response := usage_limit_response(request.user, self.team_id):
@@ -2460,6 +2482,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
description="Organization reached its PostHog Desktop usage limit",
),
502: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Agent server unreachable"),
+ 503: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer,
+ description="PostHog Desktop access could not be verified",
+ ),
},
summary="Send command to task run",
description="Queue user_message JSON-RPC commands through the task workflow and forward sandbox control "
@@ -2508,20 +2534,25 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# A side question drives the agent and spends model tokens on the caller's behalf. Unlike
# user_message below, it has no Inbox surface to exempt, so every caller takes both gates.
if method == "side_question":
- if access_response := code_access_required_response(request.user):
+ if access_response := code_access_required_response(request, self.organization):
return access_response
if limit_response := usage_limit_response(request.user, self.team_id):
return limit_response
- if method == "user_message":
- # The Inbox starts interactive runs and drops the user straight into this composer,
- # so "Discuss" and scout chat replies must not require Desktop access. Their tasks
- # are server-verifiable Inbox shapes (task_exempt_from_code_access); everything else
- # is a Desktop conversation and follows the same gate as TaskViewSet.run.
+ if method in {"user_message", "permission_response", "mcp_response"}:
+ # Inbox discussion tasks are server-verifiable policy exemptions. Permission responses
+ # preserve an active sandbox during resolution failures, but known denials still block.
if not tasks_facade.task_exempt_from_code_access(task_id, self.team_id) and (
- access_response := code_access_required_response(request.user)
+ access_response := code_access_required_response(
+ request,
+ self.organization,
+ task_id=task_id,
+ fail_open_on_resolution_error=method == "permission_response",
+ )
):
return access_response
+
+ if method == "user_message":
command_params = dict(params or {})
artifact_ids = command_params.pop("artifact_ids", [])
if artifact_ids:
@@ -2596,11 +2627,16 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"get_entries",
"get_session_stats",
"get_state",
- "mcp_permission_response",
- "permission_response",
}
and not tasks_facade.task_exempt_from_code_access(task_id, self.team_id)
- and (access_response := code_access_required_response(request.user))
+ and (
+ access_response := code_access_required_response(
+ request,
+ self.organization,
+ task_id=task_id,
+ fail_open_on_resolution_error=inner_type in {"permission_response", "mcp_permission_response"},
+ )
+ )
):
return access_response
@@ -2873,6 +2909,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
429: OpenApiResponse(
response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"
),
+ 503: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer,
+ description="PostHog Desktop access could not be verified",
+ ),
},
summary="Resume task run in cloud",
description="Resume an existing task run in a cloud sandbox. Terminates any existing workflow and starts a new one.",
@@ -2894,7 +2934,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# Resume also runs in cloud: gate before handoff.
if not tasks_facade.task_exempt_from_code_access(task_id, self.team_id) and (
- access_response := code_access_required_response(request.user)
+ access_response := code_access_required_response(request, self.organization, task_id=task_id)
):
return access_response
if limit_response := usage_limit_response(request.user, self.team_id):
@@ -3499,7 +3539,7 @@ class CodeInviteViewSet(viewsets.ViewSet):
),
},
summary="Redeem invite code",
- description="Redeem a PostHog Desktop invite code to enable access.",
+ description="Redeem a PostHog Desktop invite code to enable legacy access.",
)
@action(detail=False, methods=["post"], url_path="redeem")
def redeem(self, request, **kwargs):
@@ -3519,19 +3559,19 @@ class CodeInviteViewSet(viewsets.ViewSet):
return Response({"success": True})
@extend_schema(
- responses={
- 200: OpenApiResponse(description="Access check result"),
- },
+ responses={200: OpenApiResponse(response=LegacyDesktopAccessResponseSerializer)},
summary="Check access",
- description="Check whether the authenticated user has access to PostHog Desktop and to Loops.",
+ description="Check whether the authenticated user has legacy PostHog Desktop access and Loops access.",
)
@action(detail=False, methods=["get"], url_path="check-access")
def check_access(self, request, **kwargs):
return Response(
- {
- "has_access": tasks_access.has_tasks_access(request.user),
- "has_loops_access": tasks_access.has_loops_access(request.user),
- }
+ LegacyDesktopAccessResponseSerializer(
+ {
+ "has_access": tasks_access.has_tasks_access(request.user),
+ "has_loops_access": tasks_access.has_loops_access(request.user),
+ }
+ ).data
)
diff --git a/products/tasks/backend/presentation/views/desktop_access.py b/products/tasks/backend/presentation/views/desktop_access.py
new file mode 100644
index 000000000000..f7e5b92a7098
--- /dev/null
+++ b/products/tasks/backend/presentation/views/desktop_access.py
@@ -0,0 +1,66 @@
+from typing import Any, cast
+
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from rest_framework import status, viewsets
+from rest_framework.authentication import SessionAuthentication
+from rest_framework.decorators import action
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
+from posthog.models import User
+from posthog.permissions import APIScopePermission
+
+from products.tasks.backend.facade.access import DesktopAccessResolutionError, get_desktop_access_decision
+from products.tasks.backend.presentation.serializers import (
+ DesktopAccessResponseSerializer,
+ TaskRunErrorResponseSerializer,
+)
+
+
+@extend_schema(tags=["tasks"])
+class DesktopAccessViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ authentication_classes = [
+ SessionAuthentication,
+ PersonalAPIKeyAuthentication,
+ OAuthAccessTokenAuthentication,
+ ]
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ scope_object = "task"
+ pagination_class = None
+ serializer_class = DesktopAccessResponseSerializer
+
+ @extend_schema(
+ responses={
+ 200: OpenApiResponse(response=DesktopAccessResponseSerializer),
+ 503: OpenApiResponse(response=TaskRunErrorResponseSerializer),
+ },
+ summary="Check PostHog Desktop access",
+ description="Evaluate Desktop access for the selected project and organization.",
+ )
+ @action(detail=False, methods=["get"], url_path="access", required_scopes=["llm_gateway:read"])
+ def access(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ try:
+ decision = get_desktop_access_decision(cast(User, request.user), self.organization)
+ except DesktopAccessResolutionError:
+ return Response(
+ TaskRunErrorResponseSerializer(
+ {
+ "type": "service_unavailable",
+ "code": "desktop_access_unavailable",
+ "error": "We couldn't verify PostHog Desktop access. Try again.",
+ }
+ ).data,
+ status=status.HTTP_503_SERVICE_UNAVAILABLE,
+ )
+
+ return Response(
+ DesktopAccessResponseSerializer(
+ {
+ "allowed": decision.allowed,
+ "reason": decision.reason.value if decision.reason is not None else None,
+ }
+ ).data
+ )
diff --git a/products/tasks/backend/presentation/views/loops.py b/products/tasks/backend/presentation/views/loops.py
index fcf3eb60ab07..dd3277db112a 100644
--- a/products/tasks/backend/presentation/views/loops.py
+++ b/products/tasks/backend/presentation/views/loops.py
@@ -103,7 +103,7 @@ class LoopTriggerProjectSecretApiKeyTeamSustainedThrottle(ProjectSecretApiKeyTea
class HasLoopsAccess(BasePermission):
- """Gate every Loops endpoint on `has_loops_access` (tasks access plus the `loops` flag).
+ """Gate every Loops endpoint on its independent `loops` flag.
Exempts PSAK-authenticated service calls (`trigger`, and `runs` readback): a PSAK is a
project-scoped service credential, not a real user, so the person-targeted `loops` flag
diff --git a/products/tasks/backend/routes.py b/products/tasks/backend/routes.py
index 824d43d3d31b..927c6aa819a5 100644
--- a/products/tasks/backend/routes.py
+++ b/products/tasks/backend/routes.py
@@ -5,6 +5,7 @@ import products.tasks.backend.presentation.views.loops as loops
import products.tasks.backend.presentation.views.desktop as desktop
import products.tasks.backend.presentation.views.seat_api as seats
import products.tasks.backend.presentation.views.channels_api as channels
+import products.tasks.backend.presentation.views.desktop_access as desktop_access
import products.tasks.backend.presentation.views.task_usage_api as task_usage
import products.tasks.backend.presentation.views.sandbox_pricing_api as sandbox_pricing
@@ -16,6 +17,7 @@ def register_routes(routers: RouterRegistry) -> None:
"organization_desktop_beta_terms",
["organization_id"],
)
+ routers.projects.register(r"desktop", desktop_access.DesktopAccessViewSet, "project_desktop", ["team_id"])
project_tasks_router = routers.projects.register(r"tasks", tasks.TaskViewSet, "project_tasks", ["team_id"])
project_task_runs_router = project_tasks_router.register(
r"runs", tasks.TaskRunViewSet, "project_task_runs", ["team_id", "task_id"]
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index e923545fb9e1..9aa71cae03c0 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -39,7 +39,11 @@ from posthog.utils import absolute_uri
from products.posthog_ai.backend.models.assistant import Conversation
from products.slack_app.backend.models import SlackThreadTaskMapping
-from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.access import DesktopAccessResolutionError
+from products.tasks.backend.facade import (
+ access as tasks_access,
+ api as tasks_facade,
+)
from products.tasks.backend.facade.repo_selection import RepoSelectionResult
from products.tasks.backend.facade.run_config import TaskArtifactAdapter, TaskArtifactType
from products.tasks.backend.logic.services.code_usage_gate import (
@@ -71,8 +75,6 @@ from products.tasks.backend.models import (
TASK_OWNERSHIP_VERSION_STATE_KEY,
AgentPeerMessage,
Channel,
- CodeInvite,
- CodeInviteRedemption,
SandboxCustomImage,
SandboxEnvironment,
SandboxSession,
@@ -172,6 +174,8 @@ class BaseTaskAPITest(TestCase):
user: ClassVar[User]
feature_flag_patcher: MagicMock
mock_feature_flag: MagicMock
+ desktop_access_patcher: Any
+ _desktop_access_enabled: bool
client: APIClient
@classmethod
@@ -192,15 +196,26 @@ class BaseTaskAPITest(TestCase):
# accumulates across tests (APIBaseTest clears it in setUp for the same reason).
cache.clear()
- # Enable tasks feature flag by default
+ self.desktop_access_patcher = patch(
+ "products.tasks.backend.logic.services.code_usage_gate.get_desktop_access_decision",
+ side_effect=lambda *_args, **_kwargs: (
+ tasks_access.DesktopAccessDecision.ALLOWED
+ if self._desktop_access_enabled
+ else tasks_access.DesktopAccessDecision.STARTUP_PLAN
+ ),
+ )
+ self.desktop_access_patcher.start()
self.set_tasks_feature_flag(True)
def tearDown(self):
if hasattr(self, "feature_flag_patcher"):
self.feature_flag_patcher.stop()
+ if hasattr(self, "desktop_access_patcher"):
+ self.desktop_access_patcher.stop()
super().tearDown()
def set_tasks_feature_flag(self, enabled=True):
+ self._desktop_access_enabled = enabled
if hasattr(self, "feature_flag_patcher"):
self.feature_flag_patcher.stop()
@@ -7834,6 +7849,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(response.json()["code"], "code_access_required")
+ self.assertEqual(response.json()["reason"], "startup_plan")
mock_usage.assert_not_called()
@patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
@@ -9253,29 +9269,6 @@ class TestTasksAPIPermissions(BaseTaskAPITest):
level=OrganizationMembership.Level.ADMIN
)
- def test_check_access_flag_on_no_redemption(self):
- self.set_tasks_feature_flag(True)
-
- response = self.client.get("/api/code/invites/check-access/")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertTrue(response.json()["has_access"])
-
- def test_check_access_flag_off_no_redemption(self):
- self.set_tasks_feature_flag(False)
-
- response = self.client.get("/api/code/invites/check-access/")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertFalse(response.json()["has_access"])
-
- def test_check_access_flag_off_with_redemption(self):
- self.set_tasks_feature_flag(False)
- invite = CodeInvite.objects.create(code="ACCESSCODE", max_redemptions=0, is_active=True)
- CodeInviteRedemption.objects.create(invite_code=invite, user=self.user)
-
- response = self.client.get("/api/code/invites/check-access/")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertTrue(response.json()["has_access"])
-
def test_authentication_required(self):
task = self.create_task()
@@ -10243,9 +10236,120 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(response.json()["code"], "code_access_required")
+ self.assertEqual(response.json()["reason"], "startup_plan")
mock_signal_followup.assert_not_called()
- @parameterized.expand([("prompt",), ("steer",), ("follow_up",), ("bash",), ("compact",), ("set_model",)])
+ @parameterized.expand(
+ [
+ ("permission_response", {"requestId": "perm-1", "optionId": "allow"}),
+ (
+ "mcp_response",
+ {
+ "requestId": "relay-1",
+ "server": "playwright",
+ "payload": {"jsonrpc": "2.0", "id": 1, "result": {"content": []}},
+ },
+ ),
+ ]
+ )
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
+ def test_command_model_resuming_response_requires_code_access(self, method, params, mock_post):
+ self.set_tasks_feature_flag(False)
+ task = self.create_task()
+ run = self._create_run_with_sandbox(task)
+
+ response = self.client.post(
+ self._command_url(task, run),
+ {"jsonrpc": "2.0", "method": method, "params": params, "id": "req-1"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.json()["code"], "code_access_required")
+ self.assertEqual(response.json()["reason"], "startup_plan")
+ mock_post.assert_not_called()
+
+ @parameterized.expand(
+ [
+ (
+ "permission_response",
+ Task.Runtime.ACP,
+ "permission_response",
+ {"requestId": "perm-1", "optionId": "allow"},
+ status.HTTP_200_OK,
+ ),
+ (
+ "pi_permission_response",
+ Task.Runtime.PI,
+ "pi/rpc",
+ {"command": {"id": "req-1", "type": "permission_response", "optionId": "allow"}},
+ status.HTTP_200_OK,
+ ),
+ (
+ "mcp_response",
+ Task.Runtime.ACP,
+ "mcp_response",
+ {
+ "requestId": "relay-1",
+ "server": "playwright",
+ "payload": {"jsonrpc": "2.0", "id": 1, "result": {"content": []}},
+ },
+ status.HTTP_503_SERVICE_UNAVAILABLE,
+ ),
+ (
+ "pi_prompt",
+ Task.Runtime.PI,
+ "pi/rpc",
+ {"command": {"id": "req-1", "type": "prompt", "message": "continue"}},
+ status.HTTP_503_SERVICE_UNAVAILABLE,
+ ),
+ ]
+ )
+ @patch(
+ "products.tasks.backend.logic.services.code_usage_gate.get_desktop_access_decision",
+ side_effect=DesktopAccessResolutionError("unavailable"),
+ )
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
+ def test_command_access_resolution_failure_only_allows_permission_responses(
+ self,
+ _name: str,
+ runtime: Task.Runtime,
+ method: str,
+ params: dict[str, Any],
+ expected_status: int,
+ mock_post: MagicMock,
+ _mock_access: MagicMock,
+ ) -> None:
+ reset_sandbox_jwt_key_cache()
+ self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "id": "req-1", "result": {"accepted": True}})
+ task = self.create_task(runtime=runtime)
+ run = self._create_run_with_sandbox(task)
+
+ response = self.client.post(
+ self._command_url(task, run),
+ {"jsonrpc": "2.0", "method": method, "params": params, "id": "req-1"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, expected_status)
+ if expected_status == status.HTTP_200_OK:
+ mock_post.assert_called_once()
+ else:
+ self.assertEqual(response.json()["code"], "desktop_access_unavailable")
+ mock_post.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("prompt",),
+ ("steer",),
+ ("follow_up",),
+ ("bash",),
+ ("compact",),
+ ("set_model",),
+ ("permission_response",),
+ ("mcp_permission_response",),
+ ]
+ )
@patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_pi_rpc_execution_requires_code_access(self, inner_type, mock_post):
self.set_tasks_feature_flag(False)
@@ -10265,6 +10369,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(response.json()["code"], "code_access_required")
+ self.assertEqual(response.json()["reason"], "startup_plan")
mock_post.assert_not_called()
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
@@ -10282,7 +10387,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
"jsonrpc": "2.0",
"method": "pi/rpc",
"id": "c1",
- "params": {"command": {"id": "c1", "type": "permission_response", "approved": True}},
+ "params": {"command": {"id": "c1", "type": "get_state"}},
},
format="json",
)
@@ -11970,6 +12075,7 @@ class TestCloudUsageGate(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(response.json()["code"], "code_access_required")
+ self.assertEqual(response.json()["reason"], "startup_plan")
mock_warm.assert_not_called()
@patch("products.tasks.backend.facade.api.warm_task_sandbox")
@@ -12050,10 +12156,47 @@ class TestCloudUsageGate(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(response.json()["code"], "code_access_required")
+ self.assertEqual(response.json()["reason"], "startup_plan")
self.assertFalse(TaskRun.objects.filter(task=task).exists())
mock_gate.assert_not_called()
mock_workflow.assert_not_called()
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage", return_value=None)
+ def test_task_bound_internal_run_bypasses_access_for_its_own_task(self, _mock_gate, mock_workflow):
+ self.set_tasks_feature_flag(False)
+ task = self.create_task()
+ client = self._sandbox_oauth_client(task.id, internal_scope=True)
+
+ response = client.post(
+ f"/api/projects/@current/tasks/{task.id}/run/",
+ {"mode": "background"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertTrue(TaskRun.objects.filter(task=task).exists())
+ mock_workflow.assert_called_once()
+
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
+ def test_task_bound_internal_run_cannot_bypass_access_for_another_task(self, mock_gate, mock_workflow):
+ self.set_tasks_feature_flag(False)
+ bound_task = self.create_task()
+ other_task = self.create_task()
+ client = self._sandbox_oauth_client(bound_task.id, internal_scope=True)
+
+ response = client.post(
+ f"/api/projects/@current/tasks/{other_task.id}/run/",
+ {"mode": "background"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertFalse(TaskRun.objects.filter(task=other_task).exists())
+ mock_gate.assert_not_called()
+ mock_workflow.assert_not_called()
+
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
@patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
def test_run_forged_signal_report_origin_without_report_still_403s(self, mock_gate, mock_workflow):
@@ -12072,6 +12215,7 @@ class TestCloudUsageGate(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(response.json()["code"], "code_access_required")
+ self.assertEqual(response.json()["reason"], "startup_plan")
mock_workflow.assert_not_called()
@patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
@@ -12136,6 +12280,7 @@ class TestCloudUsageGate(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(response.json()["code"], "code_access_required")
+ self.assertEqual(response.json()["reason"], "startup_plan")
self.assertFalse(TaskRun.objects.filter(task=task).exists())
mock_gate.assert_not_called()
@@ -12301,6 +12446,7 @@ class TestCloudUsageGate(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(response.json()["code"], "code_access_required")
+ self.assertEqual(response.json()["reason"], "startup_plan")
run.refresh_from_db()
self.assertEqual(run.status, TaskRun.Status.QUEUED)
@@ -12323,6 +12469,7 @@ class TestCloudUsageGate(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(response.json()["code"], "code_access_required")
+ self.assertEqual(response.json()["reason"], "startup_plan")
@patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
def test_create_local_run_is_not_gated(self, mock_gate):
@@ -12418,9 +12565,9 @@ class TestCloudUsageGate(BaseTaskAPITest):
self, _name, origin, gate_return, expected_status, mock_gate, _mock_workflow
):
# Inbox tasks (report "Create PR" / "Discuss", scout chat) are entitled through
- # self-driving, not PostHog Desktop, so they run with the `tasks` flag off — where a
- # plain task 403s (see test_run_without_code_access_returns_403_before_usage_check).
- # The usage cost-backstop must still fire on the entitlement-bypassed path.
+ # self-driving, not PostHog Desktop, so they run while the human Desktop policy denies
+ # access. A plain task returns 403 in the same state. The usage cost backstop must still
+ # fire on the entitlement-bypassed path.
self.set_tasks_feature_flag(False)
mock_gate.return_value = gate_return
task = self._inbox_task(origin)
@@ -12526,13 +12673,18 @@ class TestUsageLimitResponse(TestCase):
self.assertEqual(response.data["code"], "usage_limit_exceeded")
self.assertEqual(response.data["limit_type"], "burst")
- @patch("products.tasks.backend.logic.services.code_usage_gate.has_tasks_access", return_value=False)
- def test_code_access_required_response_is_structured(self, _mock_access):
- response = code_access_required_response(MagicMock())
+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_desktop_access_decision")
+ def test_code_access_required_response_is_structured(self, mock_access):
+ mock_access.return_value = tasks_access.DesktopAccessDecision.STARTUP_PLAN
+ request = MagicMock()
+ request.successful_authenticator = None
+ organization = MagicMock(id=1)
+ response = code_access_required_response(request, organization)
assert response is not None
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(response.data["code"], "code_access_required")
+ self.assertEqual(response.data["reason"], "startup_plan")
def _make_custom_image(*, team: Team, user: User, **kwargs) -> SandboxCustomImage:
diff --git a/products/tasks/backend/tests/test_desktop_access.py b/products/tasks/backend/tests/test_desktop_access.py
new file mode 100644
index 000000000000..4ef5fb6a4eeb
--- /dev/null
+++ b/products/tasks/backend/tests/test_desktop_access.py
@@ -0,0 +1,244 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from django.core.cache import cache
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models import Organization, OrganizationMembership, Team
+
+from products.tasks.backend.access import (
+ DESKTOP_ACCESS_GATE_FLAG,
+ DesktopAccessReason,
+ DesktopAccessResolutionError,
+ get_desktop_access_decision,
+)
+from products.tasks.backend.logic.services.code_usage_gate import code_access_required_response
+from products.tasks.backend.models import CodeInvite, CodeInviteRedemption
+
+from ee.billing.billing_manager import OrganizationFundingStatus, PrepaidCreditState, StartupProgramLabel
+
+
+class TestDesktopAccessPolicy(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+ self.feature_flag_patcher = patch("products.tasks.backend.access.get_feature_flag_or_none")
+ self.mock_feature_flag = self.feature_flag_patcher.start()
+
+ def feature_flag_value(flag_key: str, *_args: object, **_kwargs: object) -> bool:
+ return flag_key == DESKTOP_ACCESS_GATE_FLAG
+
+ self.mock_feature_flag.side_effect = feature_flag_value
+
+ def tearDown(self) -> None:
+ self.feature_flag_patcher.stop()
+ super().tearDown()
+
+ @parameterized.expand(
+ [
+ ("normal", None, PrepaidCreditState.NONE, True, None),
+ (
+ "startup",
+ "Startup",
+ PrepaidCreditState.NONE,
+ False,
+ DesktopAccessReason.STARTUP_PLAN,
+ ),
+ ("yc", "YC", PrepaidCreditState.NONE, False, DesktopAccessReason.STARTUP_PLAN),
+ ("pending", None, PrepaidCreditState.PENDING, False, DesktopAccessReason.PREPAID_CREDITS),
+ ("active", None, PrepaidCreditState.ACTIVE, False, DesktopAccessReason.PREPAID_CREDITS),
+ ("exhausted", None, PrepaidCreditState.EXHAUSTED, True, None),
+ ("expired", None, PrepaidCreditState.EXPIRED, True, None),
+ (
+ "combined",
+ "Startup",
+ PrepaidCreditState.ACTIVE,
+ False,
+ DesktopAccessReason.STARTUP_PLAN,
+ ),
+ ]
+ )
+ @patch("products.tasks.backend.access._get_funding_status")
+ def test_policy_matrix(
+ self,
+ _name: str,
+ startup_program_label: StartupProgramLabel | None,
+ prepaid_credit_state: PrepaidCreditState,
+ expected_allowed: bool,
+ expected_reason: DesktopAccessReason | None,
+ mock_funding,
+ ) -> None:
+ mock_funding.return_value = OrganizationFundingStatus(
+ startup_program_label=startup_program_label,
+ prepaid_credit_state=prepaid_credit_state,
+ )
+
+ decision = get_desktop_access_decision(self.user, self.organization)
+
+ self.assertEqual(decision.allowed, expected_allowed)
+ self.assertEqual(decision.reason, expected_reason)
+
+ @patch("products.tasks.backend.access._get_funding_status")
+ @patch("products.tasks.backend.access.feature_enabled_or_false", return_value=True)
+ def test_rollout_flag_off_preserves_legacy_feature_flag_access(self, _mock_legacy_flag, mock_funding) -> None:
+ self.mock_feature_flag.side_effect = [False]
+
+ decision = get_desktop_access_decision(self.user, self.organization)
+
+ self.assertTrue(decision.allowed)
+ self.assertEqual(self.mock_feature_flag.call_count, 1)
+ mock_funding.assert_not_called()
+
+ @patch("products.tasks.backend.access._get_funding_status")
+ @patch("products.tasks.backend.access.feature_enabled_or_false", return_value=False)
+ def test_rollout_flag_off_preserves_legacy_invite_access(self, _mock_legacy_flag, mock_funding) -> None:
+ invite = CodeInvite.objects.create(code="LEGACYCODE", max_redemptions=1, is_active=True)
+ CodeInviteRedemption.objects.create(invite_code=invite, user=self.user)
+ self.mock_feature_flag.side_effect = [False]
+
+ decision = get_desktop_access_decision(self.user, self.organization)
+
+ self.assertTrue(decision.allowed)
+ mock_funding.assert_not_called()
+
+ @patch("products.tasks.backend.access._get_funding_status")
+ @patch("products.tasks.backend.access.feature_enabled_or_false", return_value=False)
+ def test_rollout_flag_off_preserves_legacy_denial(self, _mock_legacy_flag, mock_funding) -> None:
+ self.mock_feature_flag.side_effect = [False]
+
+ decision = get_desktop_access_decision(self.user, self.organization)
+
+ self.assertFalse(decision.allowed)
+ self.assertIsNone(decision.reason)
+ mock_funding.assert_not_called()
+
+ @patch("products.tasks.backend.access._get_funding_status")
+ def test_indeterminate_rollout_flag_fails_closed(self, mock_funding) -> None:
+ self.mock_feature_flag.side_effect = [None]
+
+ with self.assertRaises(DesktopAccessResolutionError):
+ get_desktop_access_decision(self.user, self.organization)
+
+ self.assertEqual(self.mock_feature_flag.call_count, 1)
+ mock_funding.assert_not_called()
+
+ @patch("products.tasks.backend.access._get_funding_status")
+ def test_override_grants_access_before_funding_resolution(self, mock_funding) -> None:
+ self.mock_feature_flag.side_effect = [True, True]
+
+ decision = get_desktop_access_decision(self.user, self.organization)
+
+ self.assertTrue(decision.allowed)
+ mock_funding.assert_not_called()
+
+ @patch(
+ "products.tasks.backend.logic.services.code_usage_gate.get_desktop_access_decision",
+ side_effect=DesktopAccessResolutionError("unavailable"),
+ )
+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_authenticator_scopes", return_value=[])
+ def test_compute_gate_fails_closed_on_resolution_error(self, _mock_scopes, _mock_decision) -> None:
+ response = code_access_required_response(MagicMock(), self.organization)
+
+ self.assertIsNotNone(response)
+ assert response is not None
+ self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)
+ self.assertEqual(response.data["code"], "desktop_access_unavailable")
+
+ @patch("products.tasks.backend.access._get_funding_status")
+ def test_access_code_does_not_affect_authorization_after_rollout(self, mock_funding) -> None:
+ invite = CodeInvite.objects.create(code="ACCESSCODE", max_redemptions=1, is_active=True)
+ CodeInviteRedemption.objects.create(invite_code=invite, user=self.user)
+ mock_funding.return_value = OrganizationFundingStatus(
+ startup_program_label="Startup",
+ prepaid_credit_state=PrepaidCreditState.NONE,
+ )
+
+ decision = get_desktop_access_decision(self.user, self.organization)
+
+ self.assertFalse(decision.allowed)
+ self.assertEqual(decision.reason, DesktopAccessReason.STARTUP_PLAN)
+
+ @parameterized.expand([(None,), ("control",), ("false",)])
+ def test_indeterminate_feature_flag_fails_closed(self, flag_value) -> None:
+ self.mock_feature_flag.side_effect = [True, flag_value]
+
+ with self.assertRaises(DesktopAccessResolutionError):
+ get_desktop_access_decision(self.user, self.organization)
+
+ @patch(
+ "products.tasks.backend.access._get_funding_status",
+ side_effect=DesktopAccessResolutionError("unavailable"),
+ )
+ def test_funding_failure_fails_closed(self, _mock_funding) -> None:
+ with self.assertRaises(DesktopAccessResolutionError):
+ get_desktop_access_decision(self.user, self.organization)
+
+ @patch("products.tasks.backend.access._get_funding_status")
+ def test_project_endpoint_is_scoped_to_each_organization(self, mock_funding) -> None:
+ other_organization = Organization.objects.create(name="Other organization")
+ other_team = Team.objects.create(organization=other_organization, name="Other project")
+ OrganizationMembership.objects.create(
+ organization=other_organization,
+ user=self.user,
+ level=OrganizationMembership.Level.MEMBER,
+ )
+
+ def funding_status(_user, organization: Organization) -> OrganizationFundingStatus:
+ if organization.id == self.organization.id:
+ return OrganizationFundingStatus(
+ startup_program_label=None,
+ prepaid_credit_state=PrepaidCreditState.NONE,
+ )
+ return OrganizationFundingStatus(
+ startup_program_label="YC",
+ prepaid_credit_state=PrepaidCreditState.NONE,
+ )
+
+ mock_funding.side_effect = funding_status
+
+ allowed_response = self.client.get(f"/api/projects/{self.team.id}/desktop/access/")
+ blocked_response = self.client.get(f"/api/projects/{other_team.id}/desktop/access/")
+
+ self.assertEqual(allowed_response.status_code, status.HTTP_200_OK)
+ self.assertEqual(allowed_response.json(), {"allowed": True, "reason": None})
+ self.assertEqual(blocked_response.status_code, status.HTTP_200_OK)
+ self.assertEqual(blocked_response.json(), {"allowed": False, "reason": "startup_plan"})
+
+ @patch("products.tasks.backend.presentation.views.api.tasks_access.has_loops_access", return_value=True)
+ @patch("products.tasks.backend.access.feature_enabled_or_false", return_value=True)
+ def test_legacy_endpoint_preserves_feature_flag_access(self, _mock_legacy_flag, _mock_loops) -> None:
+ response = self.client.get("/api/code/invites/check-access/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"has_access": True, "has_loops_access": True})
+
+ @patch("products.tasks.backend.presentation.views.api.tasks_access.has_loops_access", return_value=False)
+ @patch("products.tasks.backend.access.feature_enabled_or_false", return_value=False)
+ def test_legacy_endpoint_preserves_invite_access(self, _mock_legacy_flag, _mock_loops) -> None:
+ invite = CodeInvite.objects.create(code="ENDPOINTCODE", max_redemptions=1, is_active=True)
+ CodeInviteRedemption.objects.create(invite_code=invite, user=self.user)
+
+ response = self.client.get("/api/code/invites/check-access/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"has_access": True, "has_loops_access": False})
+
+ @patch("products.tasks.backend.presentation.views.api.tasks_access.has_loops_access", return_value=False)
+ @patch("products.tasks.backend.access.feature_enabled_or_false", return_value=False)
+ def test_legacy_endpoint_preserves_denial(self, _mock_legacy_flag, _mock_loops) -> None:
+ response = self.client.get("/api/code/invites/check-access/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"has_access": False, "has_loops_access": False})
+
+ @patch(
+ "products.tasks.backend.presentation.views.desktop_access.get_desktop_access_decision",
+ side_effect=DesktopAccessResolutionError,
+ )
+ def test_project_endpoint_returns_retryable_service_error(self, _mock_decision) -> None:
+ response = self.client.get(f"/api/projects/{self.team.id}/desktop/access/")
+
+ self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)
+ self.assertEqual(response.json()["code"], "desktop_access_unavailable")
diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.py
index ef0b372f0a01..92b3199c991e 100644
--- a/products/tasks/backend/tests/test_warm_facade.py
+++ b/products/tasks/backend/tests/test_warm_facade.py
@@ -12,6 +12,7 @@ from posthog.exceptions import QuotaLimitExceeded
from posthog.models import Integration, User
from products.tasks.backend.facade import (
+ access as tasks_access,
api as facade,
contracts,
)
@@ -49,16 +50,21 @@ WARM_SRC = "products.tasks.backend.logic.services.warm.SandboxWarmer"
TITLE_SRC = "products.tasks.backend.logic.services.title_generator"
+def _allow_desktop_access(test_case: APIBaseTest) -> None:
+ access_patcher = patch(
+ "products.tasks.backend.logic.services.code_usage_gate.get_desktop_access_decision",
+ return_value=tasks_access.DesktopAccessDecision.ALLOWED,
+ )
+ access_patcher.start()
+ test_case.addCleanup(access_patcher.stop)
+
+
class TestWarmTaskSandbox(APIBaseTest):
def setUp(self) -> None:
super().setUp()
self.integration = Integration.objects.create(team=self.team, kind="github", config={})
# The warm endpoint gates on Desktop access; these tests cover warm forwarding, not the gate.
- access_patcher = patch(
- "products.tasks.backend.logic.services.code_usage_gate.has_tasks_access", return_value=True
- )
- access_patcher.start()
- self.addCleanup(access_patcher.stop)
+ _allow_desktop_access(self)
def _warm(self, **overrides):
kwargs: dict[str, Any] = {
@@ -362,6 +368,7 @@ class TestCreateTaskWarmReuse(APIBaseTest):
repository_cache=[{"id": 1, "name": "posthog", "full_name": "posthog/posthog"}],
repository_cache_updated_at=django_timezone.now(),
)
+ _allow_desktop_access(self)
def _warm_run(
self,
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 72eccdd4f446..625047cea18a 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -7,11 +7,29 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+export interface LegacyDesktopAccessResponseApi {
+ /** Whether the user has legacy PostHog Desktop access. */
+ has_access: boolean
+ /** Whether the independent Loops feature is enabled. */
+ has_loops_access: boolean
+}
+
export interface CodeInviteRedeemRequestApi {
/** @maxLength 50 */
code: string
}
+/**
+ * * `startup_plan` - startup_plan
+ * * `prepaid_credits` - prepaid_credits
+ */
+export type DesktopAccessReasonEnumApi = (typeof DesktopAccessReasonEnumApi)[keyof typeof DesktopAccessReasonEnumApi]
+
+export const DesktopAccessReasonEnumApi = {
+ StartupPlan: 'startup_plan',
+ PrepaidCredits: 'prepaid_credits',
+} as const
+
/**
* * `burst` - burst
* * `sustained` - sustained
@@ -32,6 +50,11 @@ export interface TaskRunErrorResponseApi {
type?: string
/** Machine-readable error code */
code?: string
+ /** Why PostHog Desktop access was denied, when applicable.
+ *
+ * * `startup_plan` - startup_plan
+ * * `prepaid_credits` - prepaid_credits */
+ reason?: DesktopAccessReasonEnumApi
/** Request field associated with the error */
attr?: string
/** Artifact ids that could not be resolved for the run */
@@ -75,6 +98,16 @@ export interface DesktopBetaTermsAcceptanceDTOApi {
readonly is_desktop_beta_terms_accepted: boolean
}
+export interface DesktopAccessResponseApi {
+ /** Whether the selected project can use PostHog Desktop. */
+ allowed: boolean
+ /** Why Desktop access is blocked, or null when access is allowed.
+ *
+ * * `startup_plan` - startup_plan
+ * * `prepaid_credits` - prepaid_credits */
+ reason: DesktopAccessReasonEnumApi | null
+}
+
export interface LoopRepositoryEntryDTOApi {
github_integration_id: number
full_name: string
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index 04113babd24a..a040f86bb76c 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -19,7 +19,9 @@ import type {
ChannelWriteApi,
CodeInviteRedeemRequestApi,
ConnectionTokenResponseApi,
+ DesktopAccessResponseApi,
DesktopBetaTermsAcceptanceDTOApi,
+ LegacyDesktopAccessResponseApi,
LoopDTOApi,
LoopFireResultApi,
LoopPreviewDTOApi,
@@ -151,11 +153,13 @@ export const getCodeInvitesCheckAccessRetrieveUrl = () => {
}
/**
- * Check whether the authenticated user has access to PostHog Desktop and to Loops.
+ * Check whether the authenticated user has legacy PostHog Desktop access and Loops access.
* @summary Check access
*/
-export const codeInvitesCheckAccessRetrieve = async (options?: RequestInit): Promise<void> => {
- return apiMutator<void>(getCodeInvitesCheckAccessRetrieveUrl(), {
+export const codeInvitesCheckAccessRetrieve = async (
+ options?: RequestInit
+): Promise<LegacyDesktopAccessResponseApi> => {
+ return apiMutator<LegacyDesktopAccessResponseApi>(getCodeInvitesCheckAccessRetrieveUrl(), {
...options,
method: 'GET',
})
@@ -166,7 +170,7 @@ export const getCodeInvitesRedeemCreateUrl = () => {
}
/**
- * Redeem a PostHog Desktop invite code to enable access.
+ * Redeem a PostHog Desktop invite code to enable legacy access.
* @summary Redeem invite code
*/
export const codeInvitesRedeemCreate = async (
@@ -224,6 +228,24 @@ export const desktopBetaTermsCreate = async (
})
}
+export const getDesktopAccessRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/desktop/access/`
+}
+
+/**
+ * Evaluate Desktop access for the selected project and organization.
+ * @summary Check PostHog Desktop access
+ */
+export const desktopAccessRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<DesktopAccessResponseApi> => {
+ return apiMutator<DesktopAccessResponseApi>(getDesktopAccessRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getLoopsListUrl = (projectId: string, params?: LoopsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index c245b76d1574..f72c04b65d79 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -10,7 +10,7 @@
import * as zod from 'zod'
/**
- * Redeem a PostHog Desktop invite code to enable access.
+ * Redeem a PostHog Desktop invite code to enable legacy access.
* @summary Redeem invite code
*/
export const codeInvitesRedeemCreateBodyCodeMax = 50
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index c9c85d1e0802..10e9416b914f 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -104,6 +104,9 @@ tools:
code-sandbox-pricing-list:
operation: code_sandbox_pricing_list
enabled: false
+ desktop-access-retrieve:
+ operation: desktop_access_retrieve
+ enabled: false
desktop-beta-terms-create:
operation: desktop_beta_terms_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 21071e59ff51..aec8a32a8865 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -26467,6 +26467,28 @@ export namespace Schemas {
index?: number;
}
+ /**
+ * * `startup_plan` - startup_plan
+ * * `prepaid_credits` - prepaid_credits
+ */
+ export type DesktopAccessReasonEnum = typeof DesktopAccessReasonEnum[keyof typeof DesktopAccessReasonEnum];
+
+
+ export const DesktopAccessReasonEnum = {
+ StartupPlan: 'startup_plan',
+ PrepaidCredits: 'prepaid_credits',
+ } as const;
+
+ export interface DesktopAccessResponse {
+ /** Whether the selected project can use PostHog Desktop. */
+ allowed: boolean;
+ /** Why Desktop access is blocked, or null when access is allowed.
+ *
+ * * `startup_plan` - startup_plan
+ * * `prepaid_credits` - prepaid_credits */
+ reason: DesktopAccessReasonEnum | null;
+ }
+
export interface DesktopBetaTermsAcceptanceDTO {
/** Whether the organization has accepted the PostHog Desktop beta terms. */
readonly is_desktop_beta_terms_accepted: boolean;
@@ -45607,6 +45629,13 @@ export namespace Schemas {
type: LeakedKeyReportResponseTypeEnum | null;
}
+ export interface LegacyDesktopAccessResponse {
+ /** Whether the user has legacy PostHog Desktop access. */
+ has_access: boolean;
+ /** Whether the independent Loops feature is enabled. */
+ has_loops_access: boolean;
+ }
+
export interface LegalDocumentCreator {
first_name: string;
email: string;
@@ -81060,6 +81089,11 @@ export namespace Schemas {
type?: string;
/** Machine-readable error code */
code?: string;
+ /** Why PostHog Desktop access was denied, when applicable.
+ *
+ * * `startup_plan` - startup_plan
+ * * `prepaid_credits` - prepaid_credits */
+ reason?: DesktopAccessReasonEnum;
/** Request field associated with the error */
attr?: string;
/** Artifact ids that could not be resolved for the run */