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(llm-gateway): enforce project-scoped desktop access (#87118)

Jonathan Mieloob3513523557d
diff --git a/services/llm-gateway/PARITY.md b/services/llm-gateway/PARITY.md
index 1c691c71b3e4..fb9431d069a7 100644
--- a/services/llm-gateway/PARITY.md
+++ b/services/llm-gateway/PARITY.md
@@ -24,26 +24,28 @@ When a gap closes, new work uses the Go gateway and affected callers should migr
### ✅ Use the Go gateway
-| Use case | Why it fits |
-| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Customer LLM traffic | The caller uses a project secret or OAuth credential, the team wallet should pay, and standard OpenAI or Anthropic APIs are enough. |
-| Server-to-server PostHog call | A `phs_` credential, team wallet billing, and informational event properties provide enough policy and attribution. Internal spend can use a PostHog-owned team wallet. |
-| Stock SDK proxy | The caller needs OpenAI Chat Completions or Responses, Anthropic Messages or token counting, streaming, idempotency, or the model catalog. |
-| Gateway-managed routing | The caller accepts Go host selection across OpenAI, Anthropic, Azure OpenAI, Bedrock, or selected Modal models. |
+| Use case | Why it fits |
+| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Customer LLM traffic | The caller uses a project secret or OAuth credential, the team wallet should pay, and standard OpenAI or Anthropic APIs are enough. |
+| Server-to-server PostHog call | A `phs_` credential, team wallet billing, and informational event properties provide enough policy and attribution. Internal spend can use a PostHog-owned team wallet. |
+| Stock SDK proxy | The caller needs OpenAI Chat Completions or Responses, Anthropic Messages or token counting, streaming, idempotency, or the model catalog. |
+| Gateway-managed routing | The caller accepts operator-managed provider plans and health-aware selection across OpenAI, Anthropic, Azure OpenAI, Bedrock, or configured Modal, Fireworks, and Baseten hosts. |
Existing Django callers should use `build_openai_client`, `build_async_openai_client`, or `build_async_anthropic_client` from [`posthog/llm/gateway_client.py`](../../posthog/llm/gateway_client.py). The OpenAI builders forward caller-selected distinct IDs, traces, sessions, and metadata while keeping a temporary Python fallback during rollout.
### ⛔ Stay on the Python gateway for now
-| Use case | Blocking contract |
-| ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| PostHog Desktop, PostHog Code, cloud agents, onboarding, Wizard, and similar first-party products | Trusted product identity, OAuth application allowlists, OAuth user attribution, server-minted credential requirements, per-product model policy, free-tier model allowlists, and product billing or unbilled policy are not available together in Go. Desktop also requires a request-selected project validated against OAuth scope, live organization membership, and project-level access control. An `ai_product` event property is not an authorization or billing boundary. |
-| Product or user budget enforcement | Python supports product and user cost limits, plan checks, quota buckets, and requests that debit no wallet. Go currently admits against the credential owner's team wallet and does not branch settlement on credential billing mode. |
-| Agent runs a customer can start on demand | Python bounds one run's total spend against the task its credential was minted for, and picks the budget from the token's provenance rather than from the product the caller declares. Go has neither, so both the per-run ceiling and the pipeline-versus-user-started split would be lost on migration. |
-| OpenRouter, Fireworks, Cloudflare Workers AI, or Baseten | These provider paths are not available in Go. |
-| OpenAI audio transcription | Go has no transcription endpoint. |
-| OpenAI models through Anthropic Messages | Go does not provide this reverse translation. |
-| Python product usage status | The Python product usage and quota API is different from Go request usage and wallet APIs. |
+| Use case | Blocking contract |
+| ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| PostHog Desktop, PostHog Code, cloud agents, onboarding, Wizard, and similar first-party products | Trusted product identity, OAuth application allowlists, OAuth user attribution, server-minted credential requirements, per-product model policy, free-tier model allowlists, and product billing or unbilled policy are not available together in Go. Desktop also requires a request-selected project validated against OAuth scope, live organization membership, and project-level access control, followed by a Django policy decision for Startup programs and prepaid credits. An `ai_product` event property is not an authorization or billing boundary. |
+| Product or user budget enforcement | Python supports product and user cost limits, plan checks, quota buckets, and requests that debit no wallet. Go currently admits against the credential owner's team wallet and does not branch settlement on credential billing mode. |
+| Agent runs a customer can start on demand | Python bounds one run's total spend against the task its credential was minted for, and picks the budget from the token's provenance rather than from the product the caller declares. Go has neither, so both the per-run ceiling and the pipeline-versus-user-started split would be lost on migration. |
+| OpenRouter or Cloudflare Workers AI | These provider paths are not available in Go. |
+| OpenAI audio transcription | Go has no transcription endpoint. |
+| OpenAI models through Anthropic Messages | Go does not provide this reverse translation. |
+| Python product usage status | The Python product usage and quota API is different from Go request usage and wallet APIs. |
+
+For PostHog Desktop, the Python gateway maps Django credential rejections to generic access denials. Transport, server, and malformed-response failures remain retryable service errors.
### 🔎 Verify before switching
@@ -53,26 +55,27 @@ These are compatibility checks, not automatic blockers:
- **Credential:** Go accepts the credential type and projects the correct team, scope, and revocation state.
- **Billing:** identify which team owns the Go credential and should pay, then confirm its wallet is funded for the expected usage. Internal workloads can debit a PostHog-owned team wallet so spend stays attributable without charging a customer.
- **Attribution:** `X-PostHog-Distinct-Id`, `X-PostHog-Trace-Id`, and `X-PostHog-Properties` provide enough event context. Go does not derive the event distinct ID from OpenAI `user`, Anthropic `metadata.user_id`, or the OAuth user. Caller-supplied properties are not trusted policy.
-- **Session attribution:** Go main does not support native sessions yet. [PostHog/ai-gateway#383](https://github.com/PostHog/ai-gateway/pull/383) adds `X-PostHog-Session-Id` as a gateway-owned `$ai_session_id`; callers must wait for that change to deploy.
-- **Provider behavior:** health-based routing or strict `X-PostHog-Provider` pinning matches the caller's fallback requirements.
+- **Session attribution:** `X-PostHog-Session-Id` provides the required gateway-owned `$ai_session_id`.
+- **Provider deployment:** Fireworks and Baseten host support exists in Go, but the target environment must declare the required host and credentials. Baseten also requires approved-subprocessor status before deployment.
+- **Provider behavior:** operator routing policy, health-aware provider ordering, or strict `X-PostHog-Provider` pinning matches the caller's fallback requirements.
- **Wire behavior:** request fields, streaming chunks, errors, timeouts, and retries match what the caller handles.
- **Metadata:** Python per-key property and feature flag headers are converted to the Go JSON properties header.
## 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, 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, ACL-resolved OAuth team attribution, staff-owned personal-key customer-team overrides, body-derived 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, per-sandbox-run ceilings keyed on the credential's task binding, budget keys derived from token scopes rather than the declared product, 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 project-scoped PostHog Desktop policy on `posthog_code`. Django applies the access override before Startup-program and prepaid-credit restrictions; server-minted `internal_run:read` credentials bypass the human gate. |
+| 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, ACL-resolved OAuth team attribution, staff-owned personal-key customer-team overrides, body-derived 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, per-sandbox-run ceilings keyed on the credential's task binding, budget keys derived from token scopes rather than the declared product, 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 configured Modal, Fireworks, and Baseten hosts. | OpenRouter and Cloudflare Workers AI. |
+| 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 | Operator-managed provider plans, health-aware ordering, 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 | `X-PostHog-Session-Id` is recorded as the gateway-owned `$ai_session_id`. | The per-key property header can also emit `$ai_session_id`. |
## Migration checklist
@@ -88,10 +91,10 @@ Run `/migrating-llm-gateway-callers` to inventory and convert a caller.
Run `/auditing-llm-gateway-parity` after either gateway changes auth, attribution, billing, endpoints, providers, models, routing, or event metadata. The skill audits implementation sources in both repositories and updates this file without migrating callers.
-Last verified on 2026-08-22 against:
+Last verified on 2026-08-24 against:
-- `PostHog/posthog` master at `cb2ede60c0ae406f5e177654ae8bce2bc8f5447e`
-- `PostHog/ai-gateway` main at `c956a21b4a6a3ec40ae8e3fecb6bccd7b188b9be`
+- `PostHog/posthog` working tree compared with master at `e579a630700a93bc6a325758015c5e1227f05267`
+- `PostHog/ai-gateway` main at `9a9826ea448b3f5fcddeb8bc09ef187963a93902`
## References
diff --git a/services/llm-gateway/README.md b/services/llm-gateway/README.md
index 4e7448c2031c..33b5121d70d3 100644
--- a/services/llm-gateway/README.md
+++ b/services/llm-gateway/README.md
@@ -265,18 +265,11 @@ 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.
+`posthog_code` additionally requires a project-scoped PostHog Desktop decision. The OAuth application allowlist only proves that the Desktop app issued the token. It does not grant Desktop access.
+
+After OAuth validates the selected project, the gateway asks Django at `GET /api/projects/{project_id}/desktop/access/`. While `posthog-desktop-access-gate` is off, Django preserves the existing `tasks` flag and invite-code policy. When rollout is on, Django applies `posthog-desktop-access-override` before Startup-program and prepaid-credit restrictions. The gateway preserves `code_access_required` as its error code and forwards `startup_plan` or `prepaid_credits` when Django provides a reason. Server-minted credentials carrying `internal_run:read` bypass the human gate because their run already passed Django's trusted task path.
+
+The check fails closed. Django transport errors, 404, 429, 5xx responses, and malformed payloads return `503 desktop_access_unavailable` and are not cached. Django 401 and 403 credential rejections return a generic `403 code_access_required` without a funding reason and cache for 30 seconds per credential and project to limit repeated rejected lookups. Deploy the Django project endpoint everywhere before deploying this gateway contract; old gateway instances continue using the compatibility endpoint during that rollout. The Gateway allows six seconds for Django because Django can spend up to five seconds resolving a Billing cache miss. Grants cache for 60 seconds and business denials for 30 seconds. Cache keys include the user, validated team, and a non-reversible credential fingerprint. Desktop access checks use a separate outbound connection pool, capped at 10 connections per Gateway instance, so failures cannot exhaust the pool used by other policy resolvers. `LLM_GATEWAY_DESKTOP_ACCESS_GATE_ENABLED=false` disables the gateway gate.
`signals` is authorized for its own OAuth application, so a Signals run's token cannot be spent as `posthog_code` or `background_agents` by declaring a different product in the path.
Its US, EU, and dev application ids are pinned in `products/config.py` alongside every other first-party app.
diff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.py
index 6ef4e23e804b..285150a8c368 100644
--- a/services/llm-gateway/src/llm_gateway/config.py
+++ b/services/llm-gateway/src/llm_gateway/config.py
@@ -239,9 +239,10 @@ class Settings(BaseSettings):
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
+ desktop_access_cache_ttl: int = 60
+ desktop_access_denied_cache_ttl: int = 30
+ desktop_access_request_timeout: float = 6.0
+ desktop_access_max_connections: int = 10
# Billing recomputes quota at most hourly, so we tolerate slight overage rather than
# a Django roundtrip on every billable request.
diff --git a/services/llm-gateway/src/llm_gateway/dependencies.py b/services/llm-gateway/src/llm_gateway/dependencies.py
index 7e46843ee9f8..043c0905a460 100644
--- a/services/llm-gateway/src/llm_gateway/dependencies.py
+++ b/services/llm-gateway/src/llm_gateway/dependencies.py
@@ -175,21 +175,45 @@ async def enforce_desktop_access(request: Request, user: AuthenticatedUser, prod
if INTERNAL_RUN_SCOPE in (user.scopes or []):
return
+ if user.team_id is None:
+ logger.warning("desktop_access_missing_team", user_id=user.user_id)
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail={
+ "error": {
+ "message": "We couldn't verify PostHog Desktop access. Try again.",
+ "type": "service_unavailable",
+ "code": "desktop_access_unavailable",
+ }
+ },
+ )
+
resolver: DesktopAccessResolver = request.app.state.desktop_access_resolver
- if await resolver.has_access(user.user_id, upstream_auth_header(request)):
+ decision = await resolver.resolve_access(user.user_id, user.team_id, upstream_auth_header(request))
+ if decision.allowed:
return
+ if decision.resolution_failed:
+ logger.warning("desktop_access_resolution_failed", user_id=user.user_id, team_id=user.team_id)
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail={
+ "error": {
+ "message": "We couldn't verify PostHog Desktop access. Try again.",
+ "type": "service_unavailable",
+ "code": "desktop_access_unavailable",
+ }
+ },
+ )
- 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",
- }
- },
- )
+ logger.warning("desktop_access_denied", user_id=user.user_id, team_id=user.team_id, reason=decision.reason)
+ error: dict[str, object] = {
+ "message": "PostHog Desktop access is required to use this product.",
+ "type": "permission_error",
+ "code": "code_access_required",
+ }
+ if decision.reason is not None:
+ error["reason"] = decision.reason
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail={"error": error})
async def _extract_end_user_id_from_body(request: Request) -> str | None:
diff --git a/services/llm-gateway/src/llm_gateway/main.py b/services/llm-gateway/src/llm_gateway/main.py
index 50c97dcdf57b..feb2a5175cfb 100644
--- a/services/llm-gateway/src/llm_gateway/main.py
+++ b/services/llm-gateway/src/llm_gateway/main.py
@@ -222,13 +222,19 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None]:
)
app.state.http_client = httpx.AsyncClient()
+ app.state.desktop_access_http_client = httpx.AsyncClient(
+ limits=httpx.Limits(
+ max_connections=settings.desktop_access_max_connections,
+ max_keepalive_connections=settings.desktop_access_max_connections,
+ )
+ )
app.state.plan_resolver = PlanResolver(
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,
+ http_client=app.state.desktop_access_http_client,
)
app.state.quota_resolver = QuotaResolver(
redis=app.state.redis,
@@ -279,6 +285,9 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None]:
await breaker_gauge_task
except asyncio.CancelledError:
pass
+ if app.state.desktop_access_http_client:
+ await app.state.desktop_access_http_client.aclose()
+ logger.info("Desktop access HTTP client closed")
if app.state.http_client:
await app.state.http_client.aclose()
logger.info("HTTP client closed")
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
index e495fe2cbce4..c3fa65371c39 100644
--- a/services/llm-gateway/src/llm_gateway/services/desktop_access_resolver.py
+++ b/services/llm-gateway/src/llm_gateway/services/desktop_access_resolver.py
@@ -1,7 +1,9 @@
from __future__ import annotations
+import hashlib
import json
-from typing import TYPE_CHECKING
+from dataclasses import asdict, dataclass
+from typing import TYPE_CHECKING, Literal, cast
import structlog
@@ -14,10 +16,31 @@ if TYPE_CHECKING:
logger = structlog.get_logger(__name__)
DESKTOP_ACCESS_CACHE_PREFIX = "desktop_access"
+DesktopAccessReason = Literal["startup_plan", "prepaid_credits"]
+DesktopAccessStatus = Literal["allowed", "blocked", "unavailable"]
-def _redis_key(user_id: int) -> str:
- return f"{DESKTOP_ACCESS_CACHE_PREFIX}:{user_id}"
+class _CredentialRejectedError(RuntimeError):
+ pass
+
+
+@dataclass(frozen=True)
+class DesktopAccessDecision:
+ status: DesktopAccessStatus
+ reason: DesktopAccessReason | None = None
+
+ @property
+ def allowed(self) -> bool:
+ return self.status == "allowed"
+
+ @property
+ def resolution_failed(self) -> bool:
+ return self.status == "unavailable"
+
+
+def _redis_key(user_id: int, team_id: int, auth_header: str) -> str:
+ credential_fingerprint = hashlib.sha256(auth_header.encode()).hexdigest()
+ return f"{DESKTOP_ACCESS_CACHE_PREFIX}:{user_id}:{team_id}:{credential_fingerprint}"
class DesktopAccessResolver:
@@ -29,63 +52,110 @@ class DesktopAccessResolver:
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)
+ async def resolve_access(self, user_id: int, team_id: int, auth_header: str) -> DesktopAccessDecision:
+ cached = await self._get_cached(user_id, team_id, auth_header)
if cached is not None:
return cached
+ return await self._resolve_uncached(user_id, team_id, auth_header)
+
+ async def _resolve_uncached(self, user_id: int, team_id: int, auth_header: str) -> DesktopAccessDecision:
try:
- allowed = await self._fetch_access(auth_header)
+ decision = await self._fetch_access(team_id, auth_header)
+ except _CredentialRejectedError:
+ logger.warning("desktop_access_credential_rejected", user_id=user_id, team_id=team_id)
+ decision = DesktopAccessDecision(status="blocked")
+ await self._set_cached(
+ user_id,
+ team_id,
+ auth_header,
+ decision,
+ get_settings().desktop_access_denied_cache_ttl,
+ )
+ return decision
except Exception:
- logger.warning("desktop_access_fetch_failed", user_id=user_id, exc_info=True)
- allowed = False
+ logger.warning("desktop_access_fetch_failed", user_id=user_id, team_id=team_id, exc_info=True)
+ return DesktopAccessDecision(status="unavailable")
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
+ ttl = settings.desktop_access_cache_ttl if decision.allowed else settings.desktop_access_denied_cache_ttl
+ await self._set_cached(user_id, team_id, auth_header, decision, ttl)
+ return decision
- async def _get_cached(self, user_id: int) -> bool | None:
+ async def _get_cached(self, user_id: int, team_id: int, auth_header: str) -> DesktopAccessDecision | 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
+ value = await self._redis.get(_redis_key(user_id, team_id, auth_header))
+ if value is not None:
+ return self._parse_cached_decision(json.loads(value.decode()))
except Exception:
- logger.debug("desktop_access_cache_read_failed", user_id=user_id)
+ logger.debug("desktop_access_cache_read_failed", user_id=user_id, team_id=team_id)
return None
- async def _set_cached(self, user_id: int, has_access: bool, ttl: int) -> None:
+ async def _set_cached(
+ self,
+ user_id: int,
+ team_id: int,
+ auth_header: str,
+ decision: DesktopAccessDecision,
+ 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)
+ await self._redis.set(
+ _redis_key(user_id, team_id, auth_header),
+ json.dumps(asdict(decision)),
+ ex=ttl,
+ )
except Exception:
- logger.debug("desktop_access_cache_write_failed", user_id=user_id)
+ logger.debug("desktop_access_cache_write_failed", user_id=user_id, team_id=team_id)
- async def _fetch_access(self, auth_header: str) -> bool:
+ async def _fetch_access(self, team_id: int, auth_header: str) -> DesktopAccessDecision:
settings = get_settings()
if not settings.posthog_api_base_url:
- logger.warning("desktop_access_check_unconfigured")
- return False
+ raise RuntimeError("PostHog API base URL is not configured")
- url = f"{settings.posthog_api_base_url.rstrip('/')}/api/code/invites/check-access/"
- resp = await self._http.get(
+ url = f"{settings.posthog_api_base_url.rstrip('/')}/api/projects/{team_id}/desktop/access/"
+ response = 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
+ if response.status_code in (401, 403):
+ raise _CredentialRejectedError(f"Desktop access check returned {response.status_code}")
+ if response.status_code != 200:
+ raise RuntimeError(f"Desktop access check returned {response.status_code}")
+
+ return self._parse_api_decision(response.json())
+
+ @staticmethod
+ def _parse_api_decision(data: object) -> DesktopAccessDecision:
+ if not isinstance(data, dict):
+ raise ValueError("Desktop access response must be an object")
+
+ allowed = data.get("allowed")
+ if not isinstance(allowed, bool) or "reason" not in data:
+ raise ValueError("Desktop access response has invalid state")
+ status: DesktopAccessStatus = "allowed" if allowed else "blocked"
+ return DesktopAccessResolver._validate_decision(status, data["reason"])
+
+ @staticmethod
+ def _parse_cached_decision(data: object) -> DesktopAccessDecision:
+ if not isinstance(data, dict):
+ raise ValueError("Cached Desktop access decision must be an object")
+ return DesktopAccessResolver._validate_decision(data.get("status"), data.get("reason"))
+
+ @staticmethod
+ def _validate_decision(status: object, reason: object) -> DesktopAccessDecision:
+ if status not in ("allowed", "blocked", "unavailable"):
+ raise ValueError("Desktop access decision has invalid state")
+ if reason not in (None, "startup_plan", "prepaid_credits"):
+ raise ValueError("Desktop access decision has an invalid reason")
+ if status != "blocked" and reason is not None:
+ raise ValueError("Only blocked Desktop access decisions can include a reason")
+ return DesktopAccessDecision(
+ status=cast(DesktopAccessStatus, status),
+ reason=cast(DesktopAccessReason | None, reason),
+ )
diff --git a/services/llm-gateway/tests/conftest.py b/services/llm-gateway/tests/conftest.py
index f4b8107b3a6a..611a6e34fe9d 100644
--- a/services/llm-gateway/tests/conftest.py
+++ b/services/llm-gateway/tests/conftest.py
@@ -18,6 +18,7 @@ from llm_gateway.rate_limiting.cost_throttles import (
from llm_gateway.rate_limiting.runner import ThrottleRunner
from llm_gateway.rate_limiting.throttles import Throttle
from llm_gateway.request_context import request_context_var
+from llm_gateway.services.desktop_access_resolver import DesktopAccessDecision
from llm_gateway.services.plan_resolver import PlanInfo
from llm_gateway.services.quota_resolver import QuotaResourceStatus
@@ -61,7 +62,9 @@ def create_test_app(
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.desktop_access_resolver.resolve_access = AsyncMock(
+ return_value=DesktopAccessDecision(status="allowed")
+ )
app.state.anthropic_circuit_breaker = None
app.state.quota_resolver = quota_resolver
yield
diff --git a/services/llm-gateway/tests/test_dependencies.py b/services/llm-gateway/tests/test_dependencies.py
index 76498978f447..9ed16f4e8da0 100644
--- a/services/llm-gateway/tests/test_dependencies.py
+++ b/services/llm-gateway/tests/test_dependencies.py
@@ -26,6 +26,11 @@ from llm_gateway.dependencies import (
from llm_gateway.products.config import POSTHOG_CODE_US_APP_ID, SIGNALS_DEV_APP_ID
from llm_gateway.rate_limiting.cost_throttles import SandboxTaskCostThrottle
from llm_gateway.rate_limiting.throttles import ThrottleContext, ThrottleResult
+from llm_gateway.services.desktop_access_resolver import (
+ DesktopAccessDecision,
+ DesktopAccessReason,
+ DesktopAccessStatus,
+)
from llm_gateway.services.plan_resolver import PlanInfo
from llm_gateway.services.quota_resolver import QuotaResourceStatus
@@ -560,21 +565,79 @@ class TestDesktopAccessGate:
application_id=POSTHOG_CODE_US_APP_ID,
)
- def _request(self, resolver_answer: bool, path: str = "/posthog_code/v1/messages") -> Request:
+ def _request(
+ self,
+ resolver_answer: bool,
+ path: str = "/posthog_code/v1/messages",
+ reason: DesktopAccessReason | None = "startup_plan",
+ unavailable: bool = False,
+ ) -> Request:
request = _make_request({"model": "claude-sonnet-5", "messages": []}, path=path)
+ status: DesktopAccessStatus
+ if unavailable:
+ status = "unavailable"
+ elif resolver_answer:
+ status = "allowed"
+ else:
+ status = "blocked"
+ decision_reason = reason if status == "blocked" else None
resolver = MagicMock()
- resolver.has_access = AsyncMock(return_value=resolver_answer)
+ resolver.resolve_access = AsyncMock(
+ return_value=DesktopAccessDecision(
+ status=status,
+ reason=decision_reason,
+ )
+ )
request.app.state.desktop_access_resolver = resolver
return request
@pytest.mark.asyncio
- async def test_unentitled_user_blocked(self) -> None:
+ @pytest.mark.parametrize("reason", ["startup_plan", "prepaid_credits"])
+ async def test_unentitled_user_blocked_with_backend_reason(self, reason: DesktopAccessReason) -> None:
+ get_settings.cache_clear()
+ try:
+ with pytest.raises(HTTPException) as exc_info:
+ await enforce_product_access(request=self._request(False, reason=reason), user=self._oauth_user())
+ assert exc_info.value.status_code == 403
+ assert exc_info.value.detail["error"]["code"] == "code_access_required"
+ assert exc_info.value.detail["error"]["reason"] == reason
+ finally:
+ get_settings.cache_clear()
+
+ @pytest.mark.asyncio
+ async def test_legacy_denial_preserves_generic_error_shape(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())
+ await enforce_product_access(request=self._request(False, reason=None), user=self._oauth_user())
assert exc_info.value.status_code == 403
assert exc_info.value.detail["error"]["code"] == "code_access_required"
+ assert "reason" not in exc_info.value.detail["error"]
+ finally:
+ get_settings.cache_clear()
+
+ @pytest.mark.asyncio
+ async def test_resolution_failure_returns_retryable_service_error(self) -> None:
+ get_settings.cache_clear()
+ try:
+ request = self._request(False, unavailable=True)
+ with pytest.raises(HTTPException) as exc_info:
+ await enforce_product_access(request=request, user=self._oauth_user())
+ assert exc_info.value.status_code == 503
+ assert exc_info.value.detail["error"]["code"] == "desktop_access_unavailable"
+ finally:
+ get_settings.cache_clear()
+
+ @pytest.mark.asyncio
+ async def test_missing_validated_team_returns_retryable_service_error(self) -> None:
+ get_settings.cache_clear()
+ try:
+ user = self._oauth_user()
+ user.team_id = None
+ with pytest.raises(HTTPException) as exc_info:
+ await enforce_product_access(request=self._request(True), user=user)
+ assert exc_info.value.status_code == 503
+ assert exc_info.value.detail["error"]["code"] == "desktop_access_unavailable"
finally:
get_settings.cache_clear()
@@ -602,7 +665,7 @@ class TestDesktopAccessGate:
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()
+ request.app.state.desktop_access_resolver.resolve_access.assert_not_awaited()
finally:
get_settings.cache_clear()
@@ -613,7 +676,7 @@ class TestDesktopAccessGate:
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()
+ request.app.state.desktop_access_resolver.resolve_access.assert_not_awaited()
finally:
get_settings.cache_clear()
@@ -641,7 +704,7 @@ class TestDesktopAccessGate:
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()
+ request.app.state.desktop_access_resolver.resolve_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
index d15ca1fa9782..a327b296a5ff 100644
--- a/services/llm-gateway/tests/test_desktop_access_resolver.py
+++ b/services/llm-gateway/tests/test_desktop_access_resolver.py
@@ -12,7 +12,7 @@ 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
+from llm_gateway.services.desktop_access_resolver import DesktopAccessDecision, DesktopAccessResolver, _redis_key
def _make_response(status_code: int, payload: dict[str, object] | None = None) -> httpx.Response:
@@ -21,7 +21,7 @@ def _make_response(status_code: int, payload: dict[str, object] | None = None) -
status_code,
content=content,
headers={"content-type": "application/json"},
- request=httpx.Request("GET", "https://us.posthog.com/api/code/invites/check-access/"),
+ request=httpx.Request("GET", "https://us.posthog.com/api/projects/42/desktop/access/"),
)
@@ -61,10 +61,25 @@ def _clear_settings_cache() -> Iterator[None]:
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.parametrize(
+ ("payload", "expected"),
+ [
+ ({"allowed": True, "reason": None}, DesktopAccessDecision(status="allowed")),
+ ({"allowed": False, "reason": None}, DesktopAccessDecision(status="blocked")),
+ (
+ {"allowed": False, "reason": "startup_plan"},
+ DesktopAccessDecision(status="blocked", reason="startup_plan"),
+ ),
+ (
+ {"allowed": False, "reason": "prepaid_credits"},
+ DesktopAccessDecision(status="blocked", reason="prepaid_credits"),
+ ),
+ ],
+ )
+ async def test_returns_django_decision(self, payload: dict[str, object], expected: DesktopAccessDecision) -> None:
+ resolver = _make_resolver(_FakeRedis(), _make_http_client(_make_response(200, payload)))
+
+ assert await resolver.resolve_access(7, 42, "Bearer tok") == expected
@pytest.mark.asyncio
@pytest.mark.parametrize(
@@ -74,56 +89,85 @@ class TestDesktopAccessResolver:
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"),
+ pytest.param(_make_response(200, {"allowed": "yes", "reason": None}), id="malformed_allowed"),
+ pytest.param(_make_response(200, {"allowed": False}), id="missing_reason"),
],
)
- async def test_anything_but_an_explicit_grant_denies_and_is_cached_briefly(
- self, response: httpx.Response | Exception
- ) -> None:
+ async def test_resolution_failure_is_not_cached(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
+ expected = DesktopAccessDecision(status="unavailable")
+ assert await resolver.resolve_access(7, 42, "Bearer tok") == expected
+ assert await resolver.resolve_access(7, 42, "Bearer tok") == expected
- assert http.get.await_count == 1
- assert redis.ttls[_redis_key(7)] == get_settings().desktop_access_denied_cache_ttl
+ assert http.get.await_count == 2
+ assert _redis_key(7, 42, "Bearer tok") not in redis.store
@pytest.mark.asyncio
- async def test_result_is_cached_and_reused(self) -> None:
+ @pytest.mark.parametrize("status_code", [401, 403])
+ async def test_credential_rejection_is_cached_as_denial(self, status_code: int) -> None:
+ settings = get_settings()
redis = _FakeRedis()
- http = _make_http_client(_make_response(200, {"has_access": True}))
+ http = _make_http_client(_make_response(status_code))
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
+ expected = DesktopAccessDecision(status="blocked")
+ assert await resolver.resolve_access(7, 42, "Bearer restricted") == expected
+ assert await resolver.resolve_access(7, 42, "Bearer restricted") == expected
+
+ key = _redis_key(7, 42, "Bearer restricted")
assert http.get.await_count == 1
+ assert redis.ttls[key] == settings.desktop_access_denied_cache_ttl
+
+ @pytest.mark.asyncio
+ async def test_cache_is_isolated_by_user_team_and_credential(self) -> None:
+ redis = _FakeRedis()
+ http = _make_http_client(_make_response(200, {"allowed": True, "reason": None}))
+ http.get.side_effect = [
+ _make_response(200, {"allowed": True, "reason": None}),
+ _make_response(200, {"allowed": True, "reason": None}),
+ _make_response(200, {"allowed": True, "reason": None}),
+ _make_response(403),
+ ]
+ resolver = _make_resolver(redis, http)
+
+ assert (await resolver.resolve_access(7, 42, "Bearer unrestricted")).allowed is True
+ assert (await resolver.resolve_access(7, 42, "Bearer unrestricted")).allowed is True
+ assert (await resolver.resolve_access(7, 43, "Bearer unrestricted")).allowed is True
+ assert (await resolver.resolve_access(8, 42, "Bearer unrestricted")).allowed is True
+ assert (await resolver.resolve_access(7, 42, "Bearer restricted")).allowed is False
+
+ assert http.get.await_count == 4
+ assert len(redis.store) == 4
@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")
+ granted = _make_resolver(redis, _make_http_client(_make_response(200, {"allowed": True, "reason": None})))
+ await granted.resolve_access(7, 42, "Bearer tok")
+ denied = _make_resolver(
+ redis,
+ _make_http_client(_make_response(200, {"allowed": False, "reason": "startup_plan"})),
+ )
+ await denied.resolve_access(8, 42, "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 redis.ttls[_redis_key(7, 42, "Bearer tok")] == settings.desktop_access_cache_ttl
+ assert redis.ttls[_redis_key(8, 42, "Bearer tok")] == 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}))
+ async def test_calls_project_scoped_django_endpoint(self) -> None:
+ http = _make_http_client(_make_response(200, {"allowed": True, "reason": None}))
resolver = _make_resolver(None, http)
- await resolver.has_access(7, "Bearer tok")
+ await resolver.resolve_access(7, 42, "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 url == f"{base_url}/api/projects/42/desktop/access/"
assert http.get.await_args.kwargs["headers"] == {"Authorization": "Bearer tok"}