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): retire the posthog_code product on the legacy gateway (#115556)

Alessandro Pogliaghi00cdc59dc4f3
diff --git a/services/llm-gateway/PARITY.md b/services/llm-gateway/PARITY.md
index 738e5999e7ed..6f3fd015b79d 100644
--- a/services/llm-gateway/PARITY.md
+++ b/services/llm-gateway/PARITY.md
@@ -36,33 +36,30 @@ Existing Django callers should use `build_openai_client`, `build_async_openai_cl
### ⛔ Stay on the Python gateway for now
-| Use case | Blocking contract |
-| ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| PostHog Desktop, PostHog Code, cloud agents, onboarding, and similar first-party products | Go can pin product and user attribution in a scoped token, but it does not apply Django's OAuth application allowlists, project access checks, plans, or billing policy. Desktop also requires a request-selected project validated against OAuth scope, live organization membership, and project-level access control. An asserted product remains caller-controlled and is not an authorization boundary. |
-| Django plan or quota enforcement | Go supports rolling attribution budgets, a hard team cap, and per-token caps. Python still owns plan checks, quota buckets, free-model policy, and requests that debit no wallet. |
-| Agent runs a customer can start on demand | Go can cap one run with a scoped token, but the Django integration only mints tokens for server-authorized internal products. User-started runs still need Python's provenance-based policy. The wizard is the exception, and the worked example: Django runs the blocklist, the rollout switch, the program pin, the mint throttle, and the posture-tiered cap at mint, then pins the model, effort, product, and org into the token. The wizard product is retired here, so a wizard call on this gateway answers 403 with an upgrade message. |
-| 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.
-
-PostHog Code's per-user spend caps remain in Python while its callers depend on the product authorization and billing policy above.
-The Code-only switch enables the existing burst and sustained caps only for configured authenticated user IDs, whether billed or unbilled; it defaults to disabled with an empty list.
-A Go-only change would not limit these callers before migration.
-This blocker was checked on 2026-09-30 against PostHog master at `255ec0a4db39d9081fd194b2ac8ae57fdc75de32` and Go main at `da39202d10768336abd7a21fd9f27d5c8e7f2c27`.
-Go's [`GatewayCredential`](https://github.com/PostHog/ai-gateway/blob/da39202d10768336abd7a21fd9f27d5c8e7f2c27/internal/auth/gateway_credential.go) resolves a fixed team and caller-asserted attribution; it does not apply Desktop's request-selected project or Django product policy.
+| Use case | Blocking contract |
+| ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| Cloud agents, onboarding, and similar first-party products | Go can pin product and user attribution in a scoped token, but it does not apply Django's OAuth application allowlists, project access checks, plans, or billing policy. PostHog Desktop and PostHog Code mint scoped tokens on the Go gateway; the `posthog_code` product is retired here and answers 403 with reason `product_retired`. An asserted product remains caller-controlled and is not an authorization boundary. |
+| Django plan or quota enforcement | Go supports rolling attribution budgets, a hard team cap, and per-token caps. Python still owns plan checks, quota buckets, free-model policy, and requests that debit no wallet. |
+| Agent runs a customer can start on demand | Go can cap one run with a scoped token, but the Django integration only mints tokens for server-authorized internal products. User-started runs still need Python's provenance-based policy. The wizard is the exception, and the worked example: Django runs the blocklist, the rollout switch, the program pin, the mint throttle, and the posture-tiered cap at mint, then pins the model, effort, product, and org into the token. The wizard product is retired here, so a wizard call on this gateway answers 403 with an upgrade message. |
+| 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. |
+
+The `posthog_code` product is retired on this gateway.
+PostHog Desktop and PostHog Code mint scoped tokens on the Go gateway, and a `posthog_code` call here answers 403 with reason `product_retired` and a message that tells the user to update PostHog Desktop.
+The desktop access gate and the Code-only per-user spend caps stay in the code, but no request reaches them.
+The retirement also closes the gap where the `posthog_code_credits` quota check failed open: Django's quota endpoint requires `project:read`, a Code OAuth token carries only `llm_gateway:read`, so every check answered 403 and the gateway let the request through.
Open-weight models added to the Python gateway under the freeze stay there for the same reason.
-`zai-org/glm-5.3-flash` is Baseten-exclusive and reachable only by the `posthog_code` and `review_hog` products.
-Its callers are PostHog Desktop and PostHog Code, so the model depends on the OAuth application allowlists, the request-selected project validated against OAuth scope and live organization membership, and the billing policy.
+`zai-org/glm-5.3-flash` is Baseten-exclusive and reachable only by the `review_hog` product.
+Its caller is ReviewHog, which uses a shared gateway key and the product model pin.
No open-weight model is behind a per-model access flag now; the mechanism stays for the next rollout.
The Go catalog serves GLM 5.2 only, and Baseten on Go still depends on the provider deployment check below.
-`gpt-6-astra` is also Python-only because the Go catalog does not serve it, while Desktop, Code, and cloud agents require the Python product policy above.
+`gpt-6-astra` is also Python-only because the Go catalog does not serve it, while cloud agents require the Python product policy above.
`claude-opus-5-5`, `gpt-6-sol` and `gpt-6-luna` stay Python-only for the same reason: the Go catalog does not serve them.
-`gpt-6.1-sol` uses the Python product policies for Desktop, Code, Slack tasks, and background agents.
+`gpt-6.1-sol` uses the Python product policies for Slack tasks and background agents.
These callers still require the OAuth application restrictions and product billing policies above, even when the Go catalog discovers the model.
### 🔎 Verify before switching
@@ -94,7 +91,7 @@ These are compatibility checks, not automatic blockers:
| 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 product, user, obo, 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`. |
-| Request validation | Not verified for a bare-string or unknown-type content part in a Chat Completions user message. | The Chat Completions route answers 400 `invalid_request_error` before choosing a provider when a user message carries a content part outside litellm's allowed types. PostHog Code and Desktop send these through the Python gateway, and litellm otherwise raises an error with no status code that the handler reports as 500. |
+| Request validation | Not verified for a bare-string or unknown-type content part in a Chat Completions user message. | The Chat Completions route answers 400 `invalid_request_error` before choosing a provider when a user message carries a content part outside litellm's allowed types. Callers on this gateway send these, and litellm otherwise raises an error with no status code that the handler reports as 500. |
## Migration checklist
diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.py
index 87142864074d..60a3687fa1ce 100644
--- a/services/llm-gateway/src/llm_gateway/products/config.py
+++ b/services/llm-gateway/src/llm_gateway/products/config.py
@@ -70,6 +70,9 @@ WIZARD_US_APP_ID = "019a0c79-b69d-0000-f31b-b41345208c9d"
WIZARD_EU_APP_ID = "019a12d0-6edd-0000-0458-86616af3a3db"
# What a retired wizard product answers every caller with.
WIZARD_RETIRED_MESSAGE = "The wizard now runs on the PostHog AI gateway. Upgrade with: npx @posthog/wizard@latest"
+POSTHOG_CODE_RETIRED_MESSAGE = (
+ "PostHog Code no longer runs on this gateway. Update PostHog Desktop to the latest version and try again."
+)
POSTHOG_AI_US_APP_ID = "019ee060-3a0e-0000-7e9c-4e6b48dfae66"
POSTHOG_AI_EU_APP_ID = "019ee061-5620-0000-1a0d-ab1160fceeb1"
POSTHOG_AI_DEV_APP_ID = "019edb1a-cce4-0000-1f6d-682061862da9"
@@ -146,6 +149,7 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {
# Bills as posthog_code credits (pass-through model costs, no markup) — see
# get_teams_with_posthog_code_credits_used_in_period in posthog/tasks/usage_report.py.
credit_bucket=CreditBucket.POSTHOG_CODE_CREDITS,
+ denial_message=POSTHOG_CODE_RETIRED_MESSAGE,
),
# PostHog-initiated internal task runs (Task.internal=True without a more specific
# origin route — e.g. the repo-selection agent). Deliberately unbilled: this is
diff --git a/services/llm-gateway/tests/test_dependencies.py b/services/llm-gateway/tests/test_dependencies.py
index d562556f15e4..031642664040 100644
--- a/services/llm-gateway/tests/test_dependencies.py
+++ b/services/llm-gateway/tests/test_dependencies.py
@@ -27,13 +27,16 @@ from llm_gateway.dependencies import (
get_request_json,
resolve_quota,
)
-from llm_gateway.products.config import POSTHOG_CODE_US_APP_ID, SIGNALS_DEV_APP_ID, WIZARD_US_APP_ID
+from llm_gateway.products.config import (
+ POSTHOG_CODE_RETIRED_MESSAGE,
+ POSTHOG_CODE_US_APP_ID,
+ SIGNALS_DEV_APP_ID,
+ WIZARD_US_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.quota_resolver import QuotaResourceStatus
@@ -561,161 +564,6 @@ class TestServerCredentialRequirementWiring:
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",
- 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.resolve_access = AsyncMock(
- return_value=DesktopAccessDecision(
- status=status,
- reason=decision_reason,
- )
- )
- request.app.state.desktop_access_resolver = resolver
- return request
-
- @pytest.mark.asyncio
- @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, 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()
-
- @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.resolve_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.resolve_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="/django/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.resolve_access.assert_not_awaited()
- finally:
- get_settings.cache_clear()
-
-
class TestSandboxTaskIdPlumbing:
"""The whole path the per-run spend ceiling rides on: token row -> AuthenticatedUser ->
ThrottleContext -> cache key.
@@ -837,3 +685,36 @@ class TestRetiredProduct:
assert "npx @posthog/wizard@latest" in error["message"]
finally:
get_settings.cache_clear()
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("path", ["/posthog_code/v1/messages", "/array/v1/messages", "/twig/v1/messages"])
+ @pytest.mark.parametrize(
+ "scopes",
+ [["llm_gateway:read"], ["llm_gateway:read", "internal_run:read"]],
+ ids=["desktop_oauth_token", "server_minted_token"],
+ )
+ async def test_posthog_code_is_refused_before_the_desktop_gate(self, path: str, scopes: list[str]) -> None:
+ get_settings.cache_clear()
+ try:
+ request = _make_request({"model": "claude-sonnet-5", "messages": []}, path=path)
+ resolver = MagicMock()
+ resolver.resolve_access = AsyncMock(return_value=DesktopAccessDecision(status="allowed", reason=None))
+ request.app.state.desktop_access_resolver = resolver
+ user = AuthenticatedUser(
+ user_id=7,
+ team_id=1,
+ auth_method="oauth_access_token",
+ distinct_id="test-distinct-id-7",
+ scopes=scopes,
+ application_id=POSTHOG_CODE_US_APP_ID,
+ )
+ with pytest.raises(HTTPException) as exc_info:
+ await enforce_product_access(request=request, user=user)
+ assert exc_info.value.status_code == 403
+ error = exc_info.value.detail["error"]
+ assert error["code"] == "product_access_denied"
+ assert error["reason"] == "product_retired"
+ assert error["message"] == POSTHOG_CODE_RETIRED_MESSAGE
+ resolver.resolve_access.assert_not_awaited()
+ finally:
+ get_settings.cache_clear()
diff --git a/services/llm-gateway/tests/test_product_config.py b/services/llm-gateway/tests/test_product_config.py
index 3aa943f50300..bb9ba8f52d4d 100644
--- a/services/llm-gateway/tests/test_product_config.py
+++ b/services/llm-gateway/tests/test_product_config.py
@@ -17,6 +17,7 @@ from llm_gateway.products.config import (
POSTHOG_AI_US_APP_ID,
POSTHOG_CODE_DEV_APP_ID,
POSTHOG_CODE_EU_APP_ID,
+ POSTHOG_CODE_RETIRED_MESSAGE,
POSTHOG_CODE_US_APP_ID,
PRODUCT_ALIASES,
PRODUCTS,
@@ -98,24 +99,37 @@ class TestCheckProductAccess:
"oauth_access_token",
POSTHOG_CODE_US_APP_ID,
"zai-org/glm-5.3",
- True,
- None,
+ False,
+ "no longer runs on this gateway",
),
# ci allows API keys with any model (used by e2e test runs); OAuth rejected (no app IDs)
("ci", "personal_api_key", None, "claude-3-opus", True, None),
("ci", "oauth_access_token", "any-app-id", "gpt-4o", False, "not authorized"),
- # posthog_code requires OAuth with valid app ID
- ("posthog_code", "personal_api_key", None, None, False, "requires OAuth"),
- ("posthog_code", "oauth_access_token", "invalid-app-id", None, False, "not authorized"),
- ("posthog_code", "oauth_access_token", POSTHOG_CODE_US_APP_ID, None, True, None),
- ("posthog_code", "oauth_access_token", POSTHOG_CODE_EU_APP_ID, None, True, None),
+ ("posthog_code", "personal_api_key", None, None, False, "no longer runs on this gateway"),
+ ("posthog_code", "oauth_access_token", "invalid-app-id", None, False, "no longer runs on this gateway"),
(
"posthog_code",
"oauth_access_token",
POSTHOG_CODE_US_APP_ID,
- "deepseek-ai/deepseek-v4-flash-0731",
- True,
None,
+ False,
+ "no longer runs on this gateway",
+ ),
+ (
+ "posthog_code",
+ "oauth_access_token",
+ POSTHOG_CODE_EU_APP_ID,
+ None,
+ False,
+ "no longer runs on this gateway",
+ ),
+ (
+ "posthog_code",
+ "oauth_access_token",
+ POSTHOG_CODE_US_APP_ID,
+ "deepseek-ai/deepseek-v4-flash-0731",
+ False,
+ "no longer runs on this gateway",
),
# wizard is retired here: every auth method, including its own apps, gets the upgrade path
("wizard", "personal_api_key", None, "claude-3-opus", False, "npx @posthog/wizard@latest"),
@@ -207,38 +221,6 @@ class TestCheckProductAccess:
assert error is not None
assert expected_error_contains in error
- @pytest.mark.parametrize(
- "model",
- [
- "claude-fable-5",
- "claude-opus-4-5",
- "claude-opus-4-6",
- "claude-opus-4-7",
- "claude-opus-4-8",
- "claude-opus-5",
- "claude-fable-5",
- "claude-fable-5-1",
- "claude-sonnet-4-5",
- "claude-sonnet-4-6",
- "claude-sonnet-5",
- "claude-haiku-4-5",
- "gpt-5.6-sol",
- "gpt-5.6-terra",
- "gpt-5.6-luna",
- "gpt-5.5",
- "gpt-5.3-codex",
- "gpt-5.2",
- "gpt-5-mini",
- "gpt-6-astra",
- "gpt-6.1-sol",
- "deepseek-ai/deepseek-v4-flash-0731",
- ],
- )
- def test_posthog_code_allows_restricted_models_with_valid_app_id(self, model: str):
- allowed, error = check_product_access("posthog_code", "oauth_access_token", POSTHOG_CODE_US_APP_ID, model)
- assert allowed is True
- assert error is None
-
@pytest.mark.parametrize(
"model", ["deepseek-ai/deepseek-v4-flash-0731", "zai-org/glm-5.3", "zai-org/glm-5.3-flash"]
)
@@ -257,48 +239,6 @@ class TestCheckProductAccess:
assert error is not None
assert "not allowed" in error
- @pytest.mark.parametrize(
- "model",
- [
- "gpt-4o",
- "gpt-4o-mini",
- "claude-3-5-haiku-20241022",
- "claude-3-opus",
- "o1",
- ],
- )
- def test_posthog_code_rejects_non_allowed_models(self, model: str):
- allowed, error = check_product_access("posthog_code", "oauth_access_token", POSTHOG_CODE_US_APP_ID, model)
- assert allowed is False
- assert error is not None
- assert "not allowed" in error
-
- @pytest.mark.parametrize(
- "model",
- [
- "claude-fable-5",
- "claude-opus-4-5",
- "claude-opus-4-6",
- "claude-opus-4-7",
- "claude-opus-4-8",
- "claude-opus-5",
- "claude-fable-5",
- "claude-fable-5-1",
- "claude-sonnet-4-5",
- "claude-sonnet-4-6",
- "claude-sonnet-5",
- "claude-haiku-4-5",
- "gpt-5.5",
- "gpt-5.3-codex",
- "gpt-5.2",
- "gpt-5-mini",
- ],
- )
- def test_posthog_code_allows_configured_models(self, model: str):
- allowed, error = check_product_access("posthog_code", "oauth_access_token", POSTHOG_CODE_US_APP_ID, model)
- assert allowed is True
- assert error is None
-
@pytest.mark.parametrize(
"model",
[
@@ -308,8 +248,14 @@ class TestCheckProductAccess:
"gpt-5.2-turbo",
],
)
- def test_posthog_code_allows_dated_variants_via_prefix_matching(self, model: str):
- allowed, error = check_product_access("posthog_code", "oauth_access_token", POSTHOG_CODE_US_APP_ID, model)
+ def test_background_agents_allows_dated_variants_via_prefix_matching(self, model: str):
+ allowed, error = check_product_access(
+ "background_agents",
+ "oauth_access_token",
+ POSTHOG_CODE_US_APP_ID,
+ model,
+ scopes=["llm_gateway:read", "internal_run:read"],
+ )
assert allowed is True
assert error is None
@@ -323,52 +269,29 @@ class TestCheckProductAccess:
],
)
def test_model_matching_is_case_insensitive(self, model: str):
- allowed, error = check_product_access("posthog_code", "oauth_access_token", POSTHOG_CODE_US_APP_ID, model)
- assert allowed is True
- assert error is None
-
- @pytest.mark.parametrize(
- "alias",
- ["twig", "array"],
- )
- def test_legacy_aliases_resolve_to_posthog_code(self, alias: str):
- allowed, error = check_product_access(alias, "oauth_access_token", POSTHOG_CODE_US_APP_ID, "claude-sonnet-4-5")
+ allowed, error = check_product_access(
+ "background_agents",
+ "oauth_access_token",
+ POSTHOG_CODE_US_APP_ID,
+ model,
+ scopes=["llm_gateway:read", "internal_run:read"],
+ )
assert allowed is True
assert error is None
+ @pytest.mark.parametrize("product", ["posthog_code", "twig", "array"])
@pytest.mark.parametrize(
- "alias",
- ["twig", "array"],
- )
- def test_legacy_aliases_reject_non_allowed_models(self, alias: str):
- allowed, error = check_product_access(alias, "oauth_access_token", POSTHOG_CODE_US_APP_ID, "gpt-4o")
- assert allowed is False
- assert error is not None
- assert "not allowed" in error
-
- @pytest.mark.parametrize("model", sorted(BEDROCK_MODELS))
- def test_posthog_code_allows_bedrock_models(self, model: str):
- allowed, error = check_product_access("posthog_code", "oauth_access_token", POSTHOG_CODE_US_APP_ID, model)
- assert allowed is True
- assert error is None
-
- @patch(
- "llm_gateway.products.config.get_settings",
- return_value=MagicMock(debug=False, bedrock_region_name="us-east-1"),
+ "auth_method,application_id",
+ [
+ ("oauth_access_token", POSTHOG_CODE_US_APP_ID),
+ ("oauth_access_token", POSTHOG_CODE_EU_APP_ID),
+ ("personal_api_key", None),
+ ],
)
- def test_posthog_code_rejects_unallowed_model_via_bedrock_provider(self, mock_get_settings: MagicMock):
- # A model outside the allowlist with no Bedrock mapping must stay rejected on the bedrock
- # provider path — the BEDROCK_MODELS entries in the allowlist union must not resurrect it.
- allowed, error = check_product_access(
- "posthog_code",
- "oauth_access_token",
- POSTHOG_CODE_US_APP_ID,
- "claude-3-opus",
- provider="bedrock",
- )
+ def test_posthog_code_and_its_aliases_are_retired(self, product: str, auth_method: str, application_id: str | None):
+ allowed, error = check_product_access(product, auth_method, application_id, "claude-sonnet-5", scopes=["*"])
assert allowed is False
- assert error is not None
- assert "not allowed" in error
+ assert error == POSTHOG_CODE_RETIRED_MESSAGE
@pytest.mark.parametrize(
"model",
@@ -698,14 +621,6 @@ class TestServerCredentialRequirement:
assert allowed is True
assert error is None
- def test_posthog_code_does_not_require_the_marker(self):
- # desktop users reach posthog_code with a marker-less token — must keep working
- allowed, error = check_product_access(
- "posthog_code", "oauth_access_token", POSTHOG_CODE_US_APP_ID, "claude-sonnet-5", scopes=["*"]
- )
- assert allowed is True
- assert error is None
-
def test_personal_api_key_is_not_subject_to_the_marker(self):
# the shared server-side gateway key reaches signals as a PAK; the check is OAuth-only
allowed, error = check_product_access(
diff --git a/services/llm-gateway/tests/test_rate_limiting.py b/services/llm-gateway/tests/test_rate_limiting.py
index e7d6f8238377..745dad67fbb5 100644
--- a/services/llm-gateway/tests/test_rate_limiting.py
+++ b/services/llm-gateway/tests/test_rate_limiting.py
@@ -318,25 +318,18 @@ class TestFormatRetryDelay:
assert _format_retry_delay(seconds) == expected
-class TestFreeTierModelGateErrorBody:
- def test_gate_403_wire_body_carries_code_and_legacy_shim(
+class TestRetiredProductErrorBody:
+ def test_retired_product_403_keeps_the_top_level_error_envelope(
self, mock_db_pool: MagicMock, monkeypatch: pytest.MonkeyPatch
) -> None:
- """Pins the gate 403's wire shape end-to-end (raise site + exception-handler
- unwrap): a top-level error envelope, never FastAPI's {"detail": ...} nesting.
- Pre-cutover PostHog Desktop clients route this 403 by the "(rate_limit)"
- substring in the message and newer clients read the code — a regression in
- either strands installed builds in fatal-session teardown."""
from llm_gateway.auth.models import AuthenticatedUser
from llm_gateway.config import get_settings
from llm_gateway.dependencies import get_authenticated_user
- from llm_gateway.products.config import POSTHOG_CODE_US_APP_ID
+ from llm_gateway.products.config import POSTHOG_CODE_RETIRED_MESSAGE, POSTHOG_CODE_US_APP_ID
get_settings.cache_clear()
try:
app = create_test_app(mock_db_pool)
- # OAuth caller on the Desktop app whose org isn't billed for Desktop usage
- # (the conftest quota resolver reports code_usage_billing_active=False).
app.dependency_overrides[get_authenticated_user] = lambda: AuthenticatedUser(
user_id=7,
team_id=1,
@@ -361,8 +354,8 @@ class TestFreeTierModelGateErrorBody:
assert "detail" not in body
error = body["error"]
assert error["type"] == "permission_error"
- assert error["code"] == "model_gate"
- assert "claude-fable-5" in error["message"]
- assert error["message"].endswith("(rate_limit)")
+ assert error["code"] == "product_access_denied"
+ assert error["reason"] == "product_retired"
+ assert error["message"] == POSTHOG_CODE_RETIRED_MESSAGE
finally:
get_settings.cache_clear()