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.

fix(llm-gateway): require entitlement on the posthog_code product (#83548)

Charles Vien8507ede94fad
diff --git a/services/llm-gateway/PARITY.md b/services/llm-gateway/PARITY.md
index 8a3fa9b93258..e6f4c2dde555 100644
--- a/services/llm-gateway/PARITY.md
+++ b/services/llm-gateway/PARITY.md
@@ -59,19 +59,19 @@ These are compatibility checks, not automatic blockers:
## Parity map
-| Contract | Go gateway today | Python-only behavior that can block migration |
-| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Authentication | `phs_` project secrets and `pha_` OAuth credentials with the literal `llm_gateway:read` scope; credential resolves a fixed team and revocation state. | `phx_` personal keys, wildcard OAuth scope handling, product-specific API key or OAuth application rules, and Desktop's request-selected project validated against OAuth scope and live organization membership. |
-| Trusted first-party identity | No trusted product identity or product-scoped authorization boundary. | Product route selects allowlisted OAuth apps, server credential requirements, and model policy. |
-| Attribution | Distinct ID comes from `X-PostHog-Distinct-Id` or falls back to team ID. Supports trace ID, custom JSON properties, team project token, provider, usage, and cost. | OAuth user identity, body-derived OpenAI or Anthropic end-user identity, gateway-owned `$ai_product` and `$ai_billable`, per-key properties, and feature flag headers. |
-| Billing and limits | Wallet reservation and settlement, idempotency, balance read, request usage read, and front-line rate limiting. | Product and user cost windows, plans, quota buckets, product-specific free-tier model allowlists, unbilled products, and product usage status. |
-| OpenAI APIs | Chat Completions, Responses, bare Responses alias, and normalized router chat. | Audio transcription and broader LiteLLM translation. |
-| Anthropic APIs | Messages and token counting, including Bedrock-hosted models. | OpenAI models exposed through the Anthropic shape and Python-specific Bedrock opt-in behavior. |
-| Providers | OpenAI, Anthropic, Azure OpenAI, Bedrock, and selected Modal models. | OpenRouter, Fireworks, Cloudflare Workers AI, and Baseten. |
-| Models | Gateway-owned catalog, canonical IDs and aliases, capability checks, router categories, and OpenRouter-shaped pricing. | Broader LiteLLM model acceptance, Python product allowlists, and product-scoped model pricing. |
-| Routing and failure behavior | Health-based host choice, circuit breakers, hosted-provider failover, and strict provider pinning. | Caller opt-in Bedrock fallback and provider-specific Python routing. |
-| Event metadata | One `X-PostHog-Properties` JSON object plus dedicated distinct ID, trace ID, and provider headers. | `X-POSTHOG-PROPERTY-*` and `X-POSTHOG-FLAG-*` headers. |
-| Session attribution | No native session header on main. [PostHog/ai-gateway#383](https://github.com/PostHog/ai-gateway/pull/383) adds `X-PostHog-Session-Id`. | The per-key property header can emit `$ai_session_id`. |
+| Contract | Go gateway today | Python-only behavior that can block migration |
+| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Authentication | `phs_` project secrets and `pha_` OAuth credentials with the literal `llm_gateway:read` scope; credential resolves a fixed team and revocation state. | `phx_` personal keys, wildcard OAuth scope handling, product-specific API key or OAuth application rules, and Desktop's request-selected project validated against OAuth scope and live organization membership. |
+| Trusted first-party identity | No trusted product identity or product-scoped authorization boundary. | Product route selects allowlisted OAuth apps, server credential requirements, model policy, and the PostHog Desktop entitlement check on `posthog_code` (Django `has_tasks_access`, since an OAuth app allowlist alone does not prove beta membership). |
+| Attribution | Distinct ID comes from `X-PostHog-Distinct-Id` or falls back to team ID. Supports trace ID, custom JSON properties, team project token, provider, usage, and cost. | OAuth user identity, body-derived OpenAI or Anthropic end-user identity, gateway-owned `$ai_product` and `$ai_billable`, per-key properties, and feature flag headers. |
+| Billing and limits | Wallet reservation and settlement, idempotency, balance read, request usage read, and front-line rate limiting. | Product and user cost windows, plans, quota buckets, product-specific free-tier model allowlists, unbilled products, and product usage status. |
+| OpenAI APIs | Chat Completions, Responses, bare Responses alias, and normalized router chat. | Audio transcription and broader LiteLLM translation. |
+| Anthropic APIs | Messages and token counting, including Bedrock-hosted models. | OpenAI models exposed through the Anthropic shape and Python-specific Bedrock opt-in behavior. |
+| Providers | OpenAI, Anthropic, Azure OpenAI, Bedrock, and selected Modal models. | OpenRouter, Fireworks, Cloudflare Workers AI, and Baseten. |
+| Models | Gateway-owned catalog, canonical IDs and aliases, capability checks, router categories, and OpenRouter-shaped pricing. | Broader LiteLLM model acceptance, Python product allowlists, and product-scoped model pricing. |
+| Routing and failure behavior | Health-based host choice, circuit breakers, hosted-provider failover, and strict provider pinning. | Caller opt-in Bedrock fallback and provider-specific Python routing. |
+| Event metadata | One `X-PostHog-Properties` JSON object plus dedicated distinct ID, trace ID, and provider headers. | `X-POSTHOG-PROPERTY-*` and `X-POSTHOG-FLAG-*` headers. |
+| Session attribution | No native session header on main. [PostHog/ai-gateway#383](https://github.com/PostHog/ai-gateway/pull/383) adds `X-PostHog-Session-Id`. | The per-key property header can emit `$ai_session_id`. |
## Migration checklist
diff --git a/services/llm-gateway/README.md b/services/llm-gateway/README.md
index 027c58b5fd15..6680e12865a6 100644
--- a/services/llm-gateway/README.md
+++ b/services/llm-gateway/README.md
@@ -261,6 +261,19 @@ OAuth access is permitted only for products with an explicit `allowed_applicatio
Aliases: `twig`, `array` resolve to `posthog_code`; `slack-twig` resolves to `slack-posthog-code`.
+`posthog_code` additionally requires a PostHog Desktop entitlement. The OAuth application
+allowlist only proves the token was issued to the Desktop app, which any user can obtain via the
+consent flow, so the gateway also asks Django (`GET /api/code/invites/check-access/`, backed by
+`has_tasks_access`: the `tasks` flag or a redeemed invite) and rejects with
+`403 code_access_required`. Server-minted sandbox tokens (carrying `internal_run:read`) are
+exempt, since their run already passed Django's own gate.
+
+The check fails closed: anything but an explicit `has_access: true` from Django (a 4xx, a 5xx, a
+timeout, a malformed payload) is a denial, since a caller can induce lookup failures by flooding
+cold-cache requests. Grants cache for 15 minutes and denials for 60 seconds, so a Django blip
+locks an entitled user out for at most a minute after their cached grant expires.
+`LLM_GATEWAY_DESKTOP_ACCESS_GATE_ENABLED=false` disables the gate entirely.
+
### Adding a new product
1. **Add to `PRODUCTS`** in `src/llm_gateway/products/config.py`:
diff --git a/services/llm-gateway/src/llm_gateway/auth/service.py b/services/llm-gateway/src/llm_gateway/auth/service.py
index a876a9beadd0..9c8c0e3d4922 100644
--- a/services/llm-gateway/src/llm_gateway/auth/service.py
+++ b/services/llm-gateway/src/llm_gateway/auth/service.py
@@ -72,13 +72,13 @@ def upstream_auth_header(request: Request) -> str:
plan-conditioned enforcement), or quota resolution failing open.
Returns "" when the request carries no token.
"""
- api_key = request.headers.get("x-api-key")
- if api_key:
- # Not a route handler: this builds an outbound header value from the
- # caller's own credential; nothing is rendered to a response body.
- # nosemgrep: python.flask.security.audit.directly-returned-format-string.directly-returned-format-string
- return f"Bearer {api_key.strip()}"
- return request.headers.get("authorization", "")
+ token = extract_token(request)
+ if token is None:
+ return request.headers.get("authorization", "")
+ # Not a route handler: this builds an outbound header value from the
+ # caller's own credential; nothing is rendered to a response body.
+ # nosemgrep: python.flask.security.audit.directly-returned-format-string.directly-returned-format-string
+ return f"Bearer {token}"
class AuthService:
diff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.py
index d817aebd632d..5b85145277a2 100644
--- a/services/llm-gateway/src/llm_gateway/config.py
+++ b/services/llm-gateway/src/llm_gateway/config.py
@@ -211,6 +211,12 @@ class Settings(BaseSettings):
posthog_api_base_url: str = "https://us.posthog.com"
plan_cache_ttl: int = 900 # 15 minutes
+
+ desktop_access_gate_enabled: bool = True
+ desktop_access_cache_ttl: int = 900
+ desktop_access_denied_cache_ttl: int = 60
+ desktop_access_request_timeout: float = 2.0
+
# Billing recomputes quota at most hourly, so we tolerate slight overage rather than
# a Django roundtrip on every billable request.
quota_cache_ttl: int = 300 # 5 minutes
diff --git a/services/llm-gateway/src/llm_gateway/dependencies.py b/services/llm-gateway/src/llm_gateway/dependencies.py
index cd57a9f1544f..accbeca3f496 100644
--- a/services/llm-gateway/src/llm_gateway/dependencies.py
+++ b/services/llm-gateway/src/llm_gateway/dependencies.py
@@ -14,12 +14,14 @@ from llm_gateway.auth.service import (
InvalidProjectScopeError,
UnauthorizedProjectScopeError,
get_auth_service,
+ upstream_auth_header,
)
from llm_gateway.circuit_breaker import AnthropicCircuitBreaker
from llm_gateway.config import get_settings
from llm_gateway.flags import evaluate_flag
from llm_gateway.products.config import (
ALLOWED_PRODUCTS,
+ INTERNAL_RUN_SCOPE,
check_free_tier_model_access,
check_product_access,
get_product_config,
@@ -34,7 +36,8 @@ from llm_gateway.request_context import (
get_request_id,
set_throttle_context,
)
-from llm_gateway.services.plan_resolver import PlanInfo, resolve_plan_info
+from llm_gateway.services.desktop_access_resolver import DesktopAccessResolver
+from llm_gateway.services.plan_resolver import POSTHOG_CODE_PRODUCT, PlanInfo, resolve_plan_info
from llm_gateway.services.quota_resolver import QuotaResourceStatus, resolve_quota_status
logger = structlog.get_logger(__name__)
@@ -156,9 +159,39 @@ async def enforce_product_access(
if not allowed:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=error)
+
+ await enforce_desktop_access(request, user, product)
return user
+async def enforce_desktop_access(request: Request, user: AuthenticatedUser, product: str) -> None:
+ settings = get_settings()
+ if not settings.desktop_access_gate_enabled or settings.debug:
+ return
+ if product != POSTHOG_CODE_PRODUCT:
+ return
+ if user.auth_method != "oauth_access_token":
+ return
+ if INTERNAL_RUN_SCOPE in (user.scopes or []):
+ return
+
+ resolver: DesktopAccessResolver = request.app.state.desktop_access_resolver
+ if await resolver.has_access(user.user_id, upstream_auth_header(request)):
+ return
+
+ logger.warning("desktop_access_denied", user_id=user.user_id, team_id=user.team_id)
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail={
+ "error": {
+ "message": "PostHog Desktop access is required to use this product.",
+ "type": "permission_error",
+ "code": "code_access_required",
+ }
+ },
+ )
+
+
async def _extract_end_user_id_from_body(request: Request) -> str | None:
"""Extract the client-provided user identifier from the request body.
diff --git a/services/llm-gateway/src/llm_gateway/main.py b/services/llm-gateway/src/llm_gateway/main.py
index 48e3da43467d..300e54d67800 100644
--- a/services/llm-gateway/src/llm_gateway/main.py
+++ b/services/llm-gateway/src/llm_gateway/main.py
@@ -40,6 +40,7 @@ from llm_gateway.rate_limiting.denial_event import PosthogDenialCapturer
from llm_gateway.rate_limiting.runner import ThrottleRunner
from llm_gateway.request_context import RequestContext, set_request_context
from llm_gateway.services.billing_period_resolver import BillingPeriodResolver
+from llm_gateway.services.desktop_access_resolver import DesktopAccessResolver
from llm_gateway.services.plan_resolver import PlanResolver
from llm_gateway.services.quota_resolver import QuotaResolver
@@ -223,6 +224,10 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None]:
redis=app.state.redis,
http_client=app.state.http_client,
)
+ app.state.desktop_access_resolver = DesktopAccessResolver(
+ redis=app.state.redis,
+ http_client=app.state.http_client,
+ )
app.state.quota_resolver = QuotaResolver(
redis=app.state.redis,
http_client=app.state.http_client,
diff --git a/services/llm-gateway/src/llm_gateway/services/desktop_access_resolver.py b/services/llm-gateway/src/llm_gateway/services/desktop_access_resolver.py
new file mode 100644
index 000000000000..e495fe2cbce4
--- /dev/null
+++ b/services/llm-gateway/src/llm_gateway/services/desktop_access_resolver.py
@@ -0,0 +1,91 @@
+from __future__ import annotations
+
+import json
+from typing import TYPE_CHECKING
+
+import structlog
+
+from llm_gateway.config import get_settings
+
+if TYPE_CHECKING:
+ import httpx
+ from redis.asyncio import Redis
+
+logger = structlog.get_logger(__name__)
+
+DESKTOP_ACCESS_CACHE_PREFIX = "desktop_access"
+
+
+def _redis_key(user_id: int) -> str:
+ return f"{DESKTOP_ACCESS_CACHE_PREFIX}:{user_id}"
+
+
+class DesktopAccessResolver:
+ def __init__(
+ self,
+ redis: Redis[bytes] | None,
+ http_client: httpx.AsyncClient,
+ ):
+ self._redis = redis
+ self._http = http_client
+
+ async def has_access(self, user_id: int, auth_header: str) -> bool:
+ cached = await self._get_cached(user_id)
+ if cached is not None:
+ return cached
+
+ try:
+ allowed = await self._fetch_access(auth_header)
+ except Exception:
+ logger.warning("desktop_access_fetch_failed", user_id=user_id, exc_info=True)
+ allowed = False
+
+ settings = get_settings()
+ ttl = settings.desktop_access_cache_ttl if allowed else settings.desktop_access_denied_cache_ttl
+ await self._set_cached(user_id, allowed, ttl)
+ return allowed
+
+ async def _get_cached(self, user_id: int) -> bool | None:
+ if not self._redis:
+ return None
+ try:
+ val = await self._redis.get(_redis_key(user_id))
+ if val is not None:
+ data = json.loads(val.decode())
+ has_access = data.get("has_access")
+ if isinstance(has_access, bool):
+ return has_access
+ except Exception:
+ logger.debug("desktop_access_cache_read_failed", user_id=user_id)
+ return None
+
+ async def _set_cached(self, user_id: int, has_access: bool, ttl: int) -> None:
+ if not self._redis:
+ return
+ try:
+ await self._redis.set(_redis_key(user_id), json.dumps({"has_access": has_access}), ex=ttl)
+ except Exception:
+ logger.debug("desktop_access_cache_write_failed", user_id=user_id)
+
+ async def _fetch_access(self, auth_header: str) -> bool:
+ settings = get_settings()
+ if not settings.posthog_api_base_url:
+ logger.warning("desktop_access_check_unconfigured")
+ return False
+
+ url = f"{settings.posthog_api_base_url.rstrip('/')}/api/code/invites/check-access/"
+ resp = await self._http.get(
+ url,
+ headers={"Authorization": auth_header},
+ timeout=settings.desktop_access_request_timeout,
+ )
+ if resp.status_code != 200:
+ logger.warning("desktop_access_check_failed", status_code=resp.status_code)
+ return False
+
+ data = resp.json()
+ has_access = data.get("has_access") if isinstance(data, dict) else None
+ if not isinstance(has_access, bool):
+ logger.warning("desktop_access_check_malformed_response")
+ return False
+ return has_access
diff --git a/services/llm-gateway/tests/conftest.py b/services/llm-gateway/tests/conftest.py
index 6bc24d12f3e2..f4b8107b3a6a 100644
--- a/services/llm-gateway/tests/conftest.py
+++ b/services/llm-gateway/tests/conftest.py
@@ -60,6 +60,8 @@ def create_test_app(
app.state.plan_resolver.get_plan = AsyncMock(return_value=PlanInfo(plan_key=None, seat_created_at=None))
app.state.billing_period_resolver = AsyncMock()
app.state.billing_period_resolver.get_period = AsyncMock(return_value=None)
+ app.state.desktop_access_resolver = AsyncMock()
+ app.state.desktop_access_resolver.has_access = AsyncMock(return_value=True)
app.state.anthropic_circuit_breaker = None
app.state.quota_resolver = quota_resolver
yield
diff --git a/services/llm-gateway/tests/test_auth.py b/services/llm-gateway/tests/test_auth.py
index a2525f2f5865..8fa450044175 100644
--- a/services/llm-gateway/tests/test_auth.py
+++ b/services/llm-gateway/tests/test_auth.py
@@ -17,6 +17,7 @@ from llm_gateway.auth.service import (
InvalidProjectScopeError,
UnauthorizedProjectScopeError,
extract_token,
+ upstream_auth_header,
)
@@ -89,6 +90,25 @@ class TestExtractToken:
assert extract_token(request) is None
+class TestUpstreamAuthHeader:
+ @pytest.mark.parametrize(
+ "headers,expected",
+ [
+ pytest.param({"authorization": "Bearer tok"}, "Bearer tok", id="standard_bearer"),
+ pytest.param({"authorization": "bearer tok"}, "Bearer tok", id="lowercase_scheme_canonicalized"),
+ pytest.param({"authorization": "BEARER tok"}, "Bearer tok", id="uppercase_scheme_canonicalized"),
+ pytest.param({"x-api-key": " tok "}, "Bearer tok", id="x_api_key_wrapped"),
+ pytest.param({"x-api-key": "key", "authorization": "Bearer other"}, "Bearer key", id="x_api_key_wins"),
+ pytest.param({"authorization": "Basic abc"}, "Basic abc", id="non_bearer_forwarded_verbatim"),
+ pytest.param({}, "", id="no_credential"),
+ ],
+ )
+ def test_forwarded_header(self, headers: dict[str, str], expected: str) -> None:
+ request = MagicMock(spec=Request)
+ request.headers = headers
+ assert upstream_auth_header(request) == expected
+
+
def _token_row(**overrides) -> dict:
row = {
"id": 1,
diff --git a/services/llm-gateway/tests/test_dependencies.py b/services/llm-gateway/tests/test_dependencies.py
index a02fc12e5af2..d54c3fe1f650 100644
--- a/services/llm-gateway/tests/test_dependencies.py
+++ b/services/llm-gateway/tests/test_dependencies.py
@@ -8,6 +8,7 @@ from starlette.datastructures import Headers
from llm_gateway.auth.models import AuthenticatedUser
from llm_gateway.auth.service import InvalidProjectScopeError, UnauthorizedProjectScopeError
from llm_gateway.baseten import BASETEN_DEEPSEEK_PUBLIC_MODEL
+from llm_gateway.config import get_settings
from llm_gateway.dependencies import (
_extract_end_user_id_from_body,
enforce_product_access,
@@ -349,8 +350,6 @@ class TestFreeTierModelGateWiring:
@pytest.mark.asyncio
async def test_multipart_transcription_model_is_gated(self, monkeypatch: pytest.MonkeyPatch) -> None:
# the gate must see form-encoded models, not just JSON ones
- from llm_gateway.config import get_settings
-
get_settings.cache_clear()
try:
request = _make_form_request(
@@ -375,8 +374,6 @@ class TestFreeTierModelGateWiring:
@pytest.mark.asyncio
async def test_gated_model_is_rejected_on_the_enforcement_path(self, monkeypatch: pytest.MonkeyPatch) -> None:
# pins that enforce_throttles actually consults the gate on the request path
- from llm_gateway.config import get_settings
-
get_settings.cache_clear()
try:
request = _make_request({"model": "claude-fable-5", "messages": []}, path="/array/v1/messages")
@@ -517,8 +514,6 @@ class TestServerCredentialRequirementWiring:
@pytest.mark.asyncio
async def test_marker_less_oauth_token_rejected_on_sibling(self, monkeypatch: pytest.MonkeyPatch) -> None:
# pins that enforce_product_access actually applies the server-credential check on the path
- from llm_gateway.config import get_settings
-
get_settings.cache_clear()
try:
request = _make_request({"model": "claude-sonnet-5", "messages": []}, path="/signals/v1/messages")
@@ -533,8 +528,6 @@ class TestServerCredentialRequirementWiring:
async def test_marker_token_allowed_on_sibling(self, monkeypatch: pytest.MonkeyPatch) -> None:
# pins that enforce_product_access forwards the token scopes; without scopes=user.scopes a
# real server-minted token (carrying the marker) would be wrongly rejected here.
- from llm_gateway.config import get_settings
-
get_settings.cache_clear()
try:
request = _make_request({"model": "claude-sonnet-5", "messages": []}, path="/signals/v1/messages")
@@ -542,3 +535,100 @@ class TestServerCredentialRequirementWiring:
assert await enforce_product_access(request=request, user=user) is user
finally:
get_settings.cache_clear()
+
+
+class TestDesktopAccessGate:
+ def _oauth_user(self, scopes: list[str] | None = None) -> AuthenticatedUser:
+ return AuthenticatedUser(
+ user_id=7,
+ team_id=1,
+ auth_method="oauth_access_token",
+ distinct_id="test-distinct-id-7",
+ scopes=scopes if scopes is not None else ["llm_gateway:read"],
+ application_id=POSTHOG_CODE_US_APP_ID,
+ )
+
+ def _request(self, resolver_answer: bool, path: str = "/posthog_code/v1/messages") -> Request:
+ request = _make_request({"model": "claude-sonnet-5", "messages": []}, path=path)
+ resolver = MagicMock()
+ resolver.has_access = AsyncMock(return_value=resolver_answer)
+ request.app.state.desktop_access_resolver = resolver
+ return request
+
+ @pytest.mark.asyncio
+ async def test_unentitled_user_blocked(self) -> None:
+ get_settings.cache_clear()
+ try:
+ with pytest.raises(HTTPException) as exc_info:
+ await enforce_product_access(request=self._request(False), user=self._oauth_user())
+ assert exc_info.value.status_code == 403
+ assert exc_info.value.detail["error"]["code"] == "code_access_required"
+ finally:
+ get_settings.cache_clear()
+
+ @pytest.mark.asyncio
+ async def test_entitled_user_allowed(self) -> None:
+ get_settings.cache_clear()
+ try:
+ user = self._oauth_user()
+ assert await enforce_product_access(request=self._request(True), user=user) is user
+ finally:
+ get_settings.cache_clear()
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "env_var",
+ [
+ pytest.param("LLM_GATEWAY_DESKTOP_ACCESS_GATE_ENABLED", id="kill_switch"),
+ pytest.param("LLM_GATEWAY_DEBUG", id="debug"),
+ ],
+ )
+ async def test_gate_short_circuits(self, monkeypatch: pytest.MonkeyPatch, env_var: str) -> None:
+ monkeypatch.setenv(env_var, "false" if env_var.endswith("GATE_ENABLED") else "true")
+ get_settings.cache_clear()
+ try:
+ request = self._request(False)
+ user = self._oauth_user()
+ assert await enforce_product_access(request=request, user=user) is user
+ request.app.state.desktop_access_resolver.has_access.assert_not_awaited()
+ finally:
+ get_settings.cache_clear()
+
+ @pytest.mark.asyncio
+ async def test_server_minted_token_exempt(self) -> None:
+ get_settings.cache_clear()
+ try:
+ request = self._request(False)
+ user = self._oauth_user(["llm_gateway:read", "internal_run:read"])
+ assert await enforce_product_access(request=request, user=user) is user
+ request.app.state.desktop_access_resolver.has_access.assert_not_awaited()
+ finally:
+ get_settings.cache_clear()
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("path", ["/array/v1/messages", "/twig/v1/messages"])
+ async def test_alias_path_is_gated(self, path: str) -> None:
+ get_settings.cache_clear()
+ try:
+ with pytest.raises(HTTPException) as exc_info:
+ await enforce_product_access(request=self._request(False, path=path), user=self._oauth_user())
+ assert exc_info.value.status_code == 403
+ finally:
+ get_settings.cache_clear()
+
+ @pytest.mark.asyncio
+ async def test_other_products_untouched(self) -> None:
+ get_settings.cache_clear()
+ try:
+ request = self._request(False, path="/wizard/v1/messages")
+ user = AuthenticatedUser(
+ user_id=7,
+ team_id=1,
+ auth_method="personal_api_key",
+ distinct_id="test-distinct-id-7",
+ scopes=["llm_gateway:read"],
+ )
+ assert await enforce_product_access(request=request, user=user) is user
+ request.app.state.desktop_access_resolver.has_access.assert_not_awaited()
+ finally:
+ get_settings.cache_clear()
diff --git a/services/llm-gateway/tests/test_desktop_access_resolver.py b/services/llm-gateway/tests/test_desktop_access_resolver.py
new file mode 100644
index 000000000000..d15ca1fa9782
--- /dev/null
+++ b/services/llm-gateway/tests/test_desktop_access_resolver.py
@@ -0,0 +1,129 @@
+from __future__ import annotations
+
+import json
+from collections.abc import Iterator
+from typing import TYPE_CHECKING, cast
+from unittest.mock import AsyncMock, MagicMock
+
+import httpx
+import pytest
+
+if TYPE_CHECKING:
+ from redis.asyncio import Redis
+
+from llm_gateway.config import get_settings
+from llm_gateway.services.desktop_access_resolver import DesktopAccessResolver, _redis_key
+
+
+def _make_response(status_code: int, payload: dict[str, object] | None = None) -> httpx.Response:
+ content = json.dumps(payload if payload is not None else {}).encode()
+ return httpx.Response(
+ status_code,
+ content=content,
+ headers={"content-type": "application/json"},
+ request=httpx.Request("GET", "https://us.posthog.com/api/code/invites/check-access/"),
+ )
+
+
+def _make_http_client(response: httpx.Response | Exception) -> MagicMock:
+ client = MagicMock()
+ if isinstance(response, Exception):
+ client.get = AsyncMock(side_effect=response)
+ else:
+ client.get = AsyncMock(return_value=response)
+ return client
+
+
+class _FakeRedis:
+ def __init__(self) -> None:
+ self.store: dict[str, bytes] = {}
+ self.ttls: dict[str, int] = {}
+
+ async def get(self, key: str) -> bytes | None:
+ return self.store.get(key)
+
+ async def set(self, key: str, value: str | bytes, ex: int | None = None) -> None:
+ self.store[key] = value if isinstance(value, bytes) else value.encode()
+ if ex is not None:
+ self.ttls[key] = ex
+
+
+def _make_resolver(redis: _FakeRedis | None, http_client: MagicMock) -> DesktopAccessResolver:
+ return DesktopAccessResolver(cast("Redis[bytes] | None", redis), http_client)
+
+
[email protected](autouse=True)
+def _clear_settings_cache() -> Iterator[None]:
+ get_settings.cache_clear()
+ yield
+ get_settings.cache_clear()
+
+
+class TestDesktopAccessResolver:
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("has_access", [True, False])
+ async def test_returns_django_answer(self, has_access: bool) -> None:
+ resolver = _make_resolver(_FakeRedis(), _make_http_client(_make_response(200, {"has_access": has_access})))
+ assert await resolver.has_access(7, "Bearer tok") is has_access
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "response",
+ [
+ pytest.param(httpx.ConnectError("boom"), id="transport_error"),
+ pytest.param(httpx.ReadTimeout("slow"), id="timeout"),
+ pytest.param(_make_response(500), id="server_error"),
+ pytest.param(_make_response(404), id="route_missing"),
+ pytest.param(_make_response(401), id="unauthorized"),
+ pytest.param(_make_response(429), id="throttled"),
+ pytest.param(_make_response(200, {"has_access": "yes"}), id="malformed_payload"),
+ ],
+ )
+ async def test_anything_but_an_explicit_grant_denies_and_is_cached_briefly(
+ self, response: httpx.Response | Exception
+ ) -> None:
+ redis = _FakeRedis()
+ http = _make_http_client(response)
+ resolver = _make_resolver(redis, http)
+
+ assert await resolver.has_access(7, "Bearer tok") is False
+ assert await resolver.has_access(7, "Bearer tok") is False
+
+ assert http.get.await_count == 1
+ assert redis.ttls[_redis_key(7)] == get_settings().desktop_access_denied_cache_ttl
+
+ @pytest.mark.asyncio
+ async def test_result_is_cached_and_reused(self) -> None:
+ redis = _FakeRedis()
+ http = _make_http_client(_make_response(200, {"has_access": True}))
+ resolver = _make_resolver(redis, http)
+
+ assert await resolver.has_access(7, "Bearer tok") is True
+ assert await resolver.has_access(7, "Bearer tok") is True
+ assert http.get.await_count == 1
+
+ @pytest.mark.asyncio
+ async def test_denial_cached_more_briefly_than_grant(self) -> None:
+ settings = get_settings()
+ redis = _FakeRedis()
+
+ granted = _make_resolver(redis, _make_http_client(_make_response(200, {"has_access": True})))
+ await granted.has_access(7, "Bearer tok")
+ denied = _make_resolver(redis, _make_http_client(_make_response(200, {"has_access": False})))
+ await denied.has_access(8, "Bearer tok")
+
+ assert redis.ttls[_redis_key(7)] == settings.desktop_access_cache_ttl
+ assert redis.ttls[_redis_key(8)] == settings.desktop_access_denied_cache_ttl
+ assert settings.desktop_access_denied_cache_ttl < settings.desktop_access_cache_ttl
+
+ @pytest.mark.asyncio
+ async def test_calls_django_check_access_endpoint(self) -> None:
+ http = _make_http_client(_make_response(200, {"has_access": True}))
+ resolver = _make_resolver(None, http)
+
+ await resolver.has_access(7, "Bearer tok")
+
+ base_url = get_settings().posthog_api_base_url.rstrip("/")
+ url = http.get.await_args.args[0]
+ assert url == f"{base_url}/api/code/invites/check-access/"
+ assert http.get.await_args.kwargs["headers"] == {"Authorization": "Bearer tok"}