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): gate posthog_code models for orgs not billed for Code usage (#70951)

Adam Bowker67486d1cecea
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index 4342d2a8cdfb..d20c0a70d2d9 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -235,6 +235,7 @@ API_SCOPES.sort((a, b) => a.objectName.localeCompare(b.objectName))
export const API_SCOPES_OMITTED_FROM_MODAL: Partial<Record<APIScopeObject, string>> = {
// INTERNAL_API_SCOPE_OBJECTS — server-minted only, never user-grantable.
clickhouse_test_cluster_perf: 'Internal: minted programmatically only.',
+ internal_run: 'Internal: marks a server-minted sandbox/agent run credential.',
signal_scout_internal: 'Internal: sandbox-only writes for the headless Signals agent.',
signal_scout_report: 'Internal: sandbox-only writes for the scout report channel.',
// OAUTH_HIDDEN_SCOPE_OBJECTS — pasteable into a PAT, but never advertised via OAuth/CLI/MCP.
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index ef2e7c066e09..2b181f66ceae 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5714,6 +5714,7 @@ export const API_SCOPE_OBJECTS = [
'insight',
'insight_variable',
'integration',
+ 'internal_run',
'legal_document',
'link',
'live_debugger',
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 2de9db046b7f..49c4d20342f9 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -65,6 +65,7 @@ APIScopeObject = Literal[
"insight",
"insight_variable",
"integration",
+ "internal_run",
"legal_document",
"link",
"live_debugger",
@@ -138,6 +139,11 @@ API_SCOPE_ACTIONS: tuple[APIScopeActions, ...] = get_args(APIScopeActions)
INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset(
{
"clickhouse_test_cluster_perf",
+ # Provenance marker on tokens minted server-side for a sandbox/agent run
+ # (never via the consent flow or a personal API key). The LLM gateway requires
+ # it on the internal products that share the PostHog Code OAuth app so a user's
+ # own credential can't reach them — see services/llm-gateway products/config.py.
+ "internal_run",
# Sandbox-only writes for the headless Signals agent (memory create/delete,
# finding emit). Read access for the same surface lives on the public
# `signal_scout` object so user-grantable PAKs can still inspect runs/memory.
diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.py
index f202896f3eda..0a696e274ae6 100644
--- a/posthog/temporal/oauth.py
+++ b/posthog/temporal/oauth.py
@@ -37,6 +37,13 @@ SandboxOAuthApplication = Literal["array", "posthog_ai"]
INTERNAL_SCOPES: list[str] = [
"task:write",
"llm_gateway:read",
+ # Provenance marker: proves a token was minted here (server-side), not obtained by a
+ # user via the consent flow or a personal API key. `internal_run` is an internal scope,
+ # so it's rejected by every user-facing scope validator and can't be forged. The LLM
+ # gateway requires it on the internal products that share the PostHog Code OAuth app
+ # (background_agents, signals, slack_app, conversations) so a user's own OAuth token
+ # can't route around the posthog_code free-tier model gate through those.
+ "internal_run:read",
]
diff --git a/services/llm-gateway/src/llm_gateway/api/models.py b/services/llm-gateway/src/llm_gateway/api/models.py
index 448167becc58..286b98cf7ad7 100644
--- a/services/llm-gateway/src/llm_gateway/api/models.py
+++ b/services/llm-gateway/src/llm_gateway/api/models.py
@@ -1,10 +1,22 @@
from typing import Literal
-from fastapi import APIRouter
+import structlog
+from fastapi import APIRouter, Request
from pydantic import BaseModel
-from llm_gateway.products.config import validate_product
+from llm_gateway.auth.service import get_auth_service
+from llm_gateway.config import get_settings
+from llm_gateway.products.config import (
+ FREE_TIER_RESTRICTION_REASON,
+ CreditBucket,
+ filter_to_free_tier_models,
+ validate_product,
+)
+from llm_gateway.rate_limiting.throttles import is_usage_unlimited
from llm_gateway.services.model_registry import get_available_models
+from llm_gateway.services.quota_resolver import resolve_quota_status
+
+logger = structlog.get_logger(__name__)
models_router = APIRouter(tags=["models"])
@@ -40,6 +52,9 @@ class ModelObject(BaseModel):
truncation_policy: TruncationPolicyConfig = TruncationPolicyConfig()
supports_parallel_tool_calls: bool = True
experimental_supported_tools: list[str] = []
+ # Free-tier gate (posthog_code): restricted models are marked, not omitted.
+ allowed: bool = True
+ restriction_reason: str | None = None
class ModelsResponse(BaseModel):
@@ -65,12 +80,47 @@ def _build_response(product: str) -> ModelsResponse:
return ModelsResponse(data=model_objects, models=model_objects)
+async def _caller_confirmed_free_tier(request: Request) -> bool:
+ """Caller is authenticated, non-staff, and their org isn't billed for Code
+ usage. Unidentifiable callers (anonymous, auth failure) are never marked;
+ quota-fetch failures read the same last-known billing bit as enforcement,
+ so marks match what requests would do. Enforcement stays the gate."""
+ try:
+ user = await get_auth_service().authenticate_request(request, request.app.state.db_pool)
+ if user is None:
+ return False
+ if is_usage_unlimited(user):
+ return False
+ if user.team_id is None:
+ # no team to bill: enforcement reads this caller as unbilled too
+ return True
+ quota_status = await resolve_quota_status(request, user.team_id, CreditBucket.POSTHOG_CODE_CREDITS.value)
+ return not quota_status.code_usage_billing_active
+ except Exception:
+ logger.warning("models_free_tier_resolution_failed", exc_info=True)
+ return False
+
+
@models_router.get("/v1/models")
async def list_models() -> ModelsResponse:
return _build_response("llm_gateway")
@models_router.get("/{product}/v1/models")
-async def list_models_for_product(product: str) -> ModelsResponse:
- validate_product(product)
- return _build_response(product)
+async def list_models_for_product(product: str, request: Request) -> ModelsResponse:
+ resolved = validate_product(product)
+ response = _build_response(product)
+
+ if resolved != "posthog_code" or not get_settings().posthog_code_model_gate_enabled:
+ return response
+ if not await _caller_confirmed_free_tier(request):
+ return response
+
+ free_ids = set(filter_to_free_tier_models([m.id for m in response.data]))
+ annotated = [
+ m
+ if m.id in free_ids
+ else m.model_copy(update={"allowed": False, "restriction_reason": FREE_TIER_RESTRICTION_REASON})
+ for m in response.data
+ ]
+ return ModelsResponse(data=annotated, models=annotated)
diff --git a/services/llm-gateway/src/llm_gateway/api/openai.py b/services/llm-gateway/src/llm_gateway/api/openai.py
index 4e1fc6ceea6e..102666f4c27f 100644
--- a/services/llm-gateway/src/llm_gateway/api/openai.py
+++ b/services/llm-gateway/src/llm_gateway/api/openai.py
@@ -245,7 +245,8 @@ async def audio_transcriptions(
user: RateLimitedUser,
request: Request,
file: Annotated[UploadFile, File()],
- model: Annotated[str, Form()] = "gpt-4o-transcribe",
+ # required, like OpenAI's API: a server default would bypass the model access checks
+ model: Annotated[str, Form()],
language: Annotated[str | None, Form()] = None,
) -> dict[str, Any]:
apply_posthog_context_from_headers(request)
@@ -258,7 +259,7 @@ async def audio_transcriptions_with_product(
product: str,
request: Request,
file: Annotated[UploadFile, File()],
- model: Annotated[str, Form()] = "gpt-4o-transcribe",
+ model: Annotated[str, Form()],
language: Annotated[str | None, Form()] = None,
) -> dict[str, Any]:
validate_product(product)
diff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.py
index 5ae039012b1c..e46fe0151cac 100644
--- a/services/llm-gateway/src/llm_gateway/config.py
+++ b/services/llm-gateway/src/llm_gateway/config.py
@@ -184,6 +184,10 @@ class Settings(BaseSettings):
user_cost_limits: dict[str, UserCostLimit] = DEFAULT_USER_COST_LIMITS
user_cost_limits_disabled: bool = False
+ # TODO: flip on when Code migrates all users to usage-based billing
+ posthog_code_model_gate_enabled: bool = False
+ posthog_code_free_tier_models: list[str] = ["@cf/zai-org/glm-5.2"]
+
default_fallback_cost_usd: float = 0.01
posthog_api_base_url: str = "https://us.posthog.com"
diff --git a/services/llm-gateway/src/llm_gateway/dependencies.py b/services/llm-gateway/src/llm_gateway/dependencies.py
index 496e37850180..904c42e5e767 100644
--- a/services/llm-gateway/src/llm_gateway/dependencies.py
+++ b/services/llm-gateway/src/llm_gateway/dependencies.py
@@ -13,13 +13,14 @@ from llm_gateway.auth.service import AuthService, get_auth_service
from llm_gateway.circuit_breaker import AnthropicCircuitBreaker
from llm_gateway.products.config import (
ALLOWED_PRODUCTS,
+ check_free_tier_model_access,
check_product_access,
get_product_config,
resolve_product_alias,
)
from llm_gateway.rate_limiting.cost_refresh import ensure_costs_fresh
from llm_gateway.rate_limiting.runner import ThrottleRunner
-from llm_gateway.rate_limiting.throttles import ThrottleContext
+from llm_gateway.rate_limiting.throttles import ThrottleContext, is_usage_unlimited
from llm_gateway.request_context import (
extract_posthog_provider_from_headers,
get_request_id,
@@ -76,18 +77,35 @@ async def get_cached_body(request: Request) -> bytes | None:
async def get_request_json(request: Request) -> dict[str, Any] | None:
+ """Parse the JSON body as a dict, caching the result for reuse — the
+ access-check chain reads it several times per request."""
+ if hasattr(request.state, "_cached_json"):
+ return request.state._cached_json
+ parsed: dict[str, Any] | None = None
body = await get_cached_body(request)
- if not body:
- return None
- try:
- data = json.loads(body)
- return data if isinstance(data, dict) else None
- except (json.JSONDecodeError, TypeError):
- return None
+ if body:
+ try:
+ data = json.loads(body)
+ parsed = data if isinstance(data, dict) else None
+ except (json.JSONDecodeError, TypeError):
+ parsed = None
+ request.state._cached_json = parsed
+ return parsed
async def get_model_from_request(request: Request) -> str | None:
- """Extract model name from request body if present."""
+ """Extract the model from the request body (JSON, or form for the
+ transcription routes). None is safe: every route requires a model at
+ validation, so such a request never reaches an upstream."""
+ content_type = request.headers.get("content-type", "").lower()
+ if content_type.startswith(("multipart/form-data", "application/x-www-form-urlencoded")):
+ try:
+ form = await request.form()
+ except Exception:
+ # malformed forms fail the endpoint's own parsing too
+ return None
+ model = form.get("model")
+ return model if isinstance(model, str) else None
data = await get_request_json(request)
if data is None:
return None
@@ -120,6 +138,7 @@ async def enforce_product_access(
application_id=user.application_id,
model=model,
provider=provider,
+ scopes=user.scopes,
)
if not allowed:
@@ -133,14 +152,8 @@ async def _extract_end_user_id_from_body(request: Request) -> str | None:
For OpenAI-compatible endpoints, this is the top-level `user` field.
For Anthropic endpoints, this is `metadata.user_id`.
"""
- body = await get_cached_body(request)
- if not body:
- return None
- try:
- data = json.loads(body)
- except (json.JSONDecodeError, TypeError):
- return None
- if not isinstance(data, dict):
+ data = await get_request_json(request)
+ if data is None:
return None
user_id = data.get("user")
@@ -206,6 +219,22 @@ async def enforce_throttles(
product=product,
)
+ model_allowed, model_error = check_free_tier_model_access(
+ product=product,
+ model=await get_model_from_request(request),
+ provider=await get_provider_from_request(request),
+ code_usage_billed=quota_status.code_usage_billing_active,
+ usage_unlimited=is_usage_unlimited(user),
+ )
+ if not model_allowed:
+ logger.warning(
+ "free_tier_model_blocked",
+ user_id=user.user_id,
+ team_id=user.team_id,
+ product=product,
+ )
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=model_error)
+
context = ThrottleContext(
user=user,
product=product,
diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.py
index 9d65d89cff58..5ec8f4d7d9a0 100644
--- a/services/llm-gateway/src/llm_gateway/products/config.py
+++ b/services/llm-gateway/src/llm_gateway/products/config.py
@@ -37,6 +37,14 @@ class ProductConfig:
# so the reporter rolls them into that bucket's credit counter, and every caller
# is blocked when the bucket's quota is exhausted.
credit_bucket: CreditBucket | None = None
+ # When True, OAuth callers must present a server-minted credential (a token carrying
+ # the internal `internal_run:read` scope). Set on the internal products that share the
+ # PostHog Code OAuth app but are only ever driven by sandbox runs — a user's own Code
+ # OAuth token can't carry an internal scope, so this stops it routing around the
+ # posthog_code free-tier model gate through these products. Personal API keys are
+ # unaffected (they reach the gateway only with an explicit, feature-gated
+ # llm_gateway:read scope, not the wildcard a consent token uses).
+ requires_server_credential: bool = False
BEDROCK_MODELS = BEDROCK_MODEL_IDS
@@ -127,12 +135,14 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {
),
allow_api_keys=False,
credit_bucket=None,
+ requires_server_credential=True,
),
"slack_app": ProductConfig(
allowed_application_ids=frozenset({POSTHOG_CODE_US_APP_ID, POSTHOG_CODE_EU_APP_ID, POSTHOG_CODE_DEV_APP_ID}),
allowed_models=_POSTHOG_CODE_AGENT_MODELS | BEDROCK_MODELS,
allow_api_keys=False,
credit_bucket=CreditBucket.AI_CREDITS,
+ requires_server_credential=True,
),
# SherlockHog (https://github.com/PostHog/SherlockHog) — the internal SRE
# bot. Authenticates with a personal API key (not OAuth), so no application
@@ -201,6 +211,7 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {
allowed_models=None, # any model — the signals pipeline picks models per stage (haiku, sonnet, ...)
allow_api_keys=True,
credit_bucket=None,
+ requires_server_credential=True,
),
"review_hog": ProductConfig(
allowed_application_ids=None,
@@ -224,6 +235,7 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {
# PostHog" per the pricing RFC — it gets its own pricing later, not posthog_code's
# pass-through bucket.
credit_bucket=None,
+ requires_server_credential=True,
),
"warehouse_semantic_enrichment": ProductConfig(
allowed_application_ids=None,
@@ -296,12 +308,56 @@ def _model_matches_product_allowlist(
)
+FREE_TIER_RESTRICTION_REASON: Final[str] = "paid_plan_required"
+
+# Internal scope stamped on every server-minted sandbox/agent token (see INTERNAL_SCOPES in
+# posthog/temporal/oauth.py). Being an internal scope, it can't be obtained through the OAuth
+# consent flow or a personal API key, so its presence proves a token was minted server-side
+# rather than held by a user. Products with requires_server_credential demand it from OAuth callers.
+INTERNAL_RUN_SCOPE: Final[str] = "internal_run:read"
+
+
+def check_free_tier_model_access(
+ product: str,
+ model: str | None,
+ provider: str | None,
+ code_usage_billed: bool,
+ usage_unlimited: bool,
+) -> tuple[bool, str | None]:
+ settings = get_settings()
+ if not settings.posthog_code_model_gate_enabled:
+ return True, None
+ if resolve_product_alias(product) != "posthog_code":
+ return True, None
+ # model=None is safe: every route requires a model at validation, so the request 422s
+ if code_usage_billed or usage_unlimited or model is None:
+ return True, None
+
+ free_models = frozenset(settings.posthog_code_free_tier_models)
+ if _model_matches_product_allowlist(model, free_models, provider=provider, settings=settings):
+ return True, None
+
+ available = ", ".join(sorted(free_models))
+ return False, (
+ f"Model '{model}' needs a paid PostHog plan. Models available on the free tier: {available}. "
+ "Add a payment method to your organization to unlock all models."
+ )
+
+
+def filter_to_free_tier_models(model_ids: list[str]) -> list[str]:
+ """Subset of model_ids on the posthog_code free tier."""
+ settings = get_settings()
+ free_models = frozenset(settings.posthog_code_free_tier_models)
+ return [m for m in model_ids if _model_matches_product_allowlist(m, free_models, settings=settings)]
+
+
def check_product_access(
product: str,
auth_method: str,
application_id: str | None,
model: str | None,
provider: str | None = None,
+ scopes: list[str] | None = None,
) -> tuple[bool, str | None]:
"""
Check if request is authorized for product.
@@ -324,6 +380,21 @@ def check_product_access(
if application_id not in allowed_application_ids:
return False, f"OAuth application not authorized for product '{product}'"
+ # Internal products that share the PostHog Code OAuth app are only ever driven by
+ # server-minted sandbox tokens; a user's own Code OAuth token would otherwise reach them
+ # and route around the posthog_code free-tier model gate. Require the internal marker that
+ # only server-minted tokens carry. OAuth-only: personal API keys reach the gateway with an
+ # explicit, feature-gated llm_gateway:read scope (a `*` PAK is rejected at auth), so the
+ # shared server-side gateway key still works here. Gated behind the same flag as the
+ # free-tier gate so it stays inert until the Code billing cutover.
+ if (
+ settings.posthog_code_model_gate_enabled
+ and config.requires_server_credential
+ and is_oauth
+ and INTERNAL_RUN_SCOPE not in (scopes or [])
+ ):
+ return False, f"Product '{product}' requires a server-minted credential"
+
if model and config.allowed_models is not None:
if not _model_matches_product_allowlist(model, config.allowed_models, provider=provider, settings=settings):
return False, f"Model '{model}' not allowed for product '{product}'"
diff --git a/services/llm-gateway/tests/test_dependencies.py b/services/llm-gateway/tests/test_dependencies.py
index a5eaee20b8ea..5b94aa8bbefd 100644
--- a/services/llm-gateway/tests/test_dependencies.py
+++ b/services/llm-gateway/tests/test_dependencies.py
@@ -8,20 +8,31 @@ from starlette.datastructures import Headers
from llm_gateway.auth.models import AuthenticatedUser
from llm_gateway.dependencies import (
_extract_end_user_id_from_body,
+ enforce_product_access,
enforce_throttles,
+ get_model_from_request,
get_provider_from_request,
+ get_request_json,
resolve_plan_and_quota,
)
+from llm_gateway.products.config import POSTHOG_CODE_US_APP_ID
from llm_gateway.rate_limiting.throttles import ThrottleContext, ThrottleResult
from llm_gateway.services.plan_resolver import PlanInfo
from llm_gateway.services.quota_resolver import QuotaResourceStatus
-def _make_request(body: dict | None = None, headers: dict[str, str] | None = None) -> Request:
+def _make_request(
+ body: dict | None = None,
+ headers: dict[str, str] | None = None,
+ path: str = "/openai/v1/chat/completions",
+) -> Request:
request = MagicMock(spec=Request)
request.state = MagicMock()
del request.state._cached_body
+ del request.state._cached_json
request.headers = Headers(headers or {})
+ # configure_mock dodges the read-only URL.path property the spec exposes
+ request.configure_mock(**{"url.path": path})
if body is not None:
raw = json.dumps(body).encode()
@@ -35,6 +46,28 @@ def _make_request(body: dict | None = None, headers: dict[str, str] | None = Non
return request
+_TRANSCRIPTION_MULTIPART_BODY = (
+ b'--boundary\r\nContent-Disposition: form-data; name="model"\r\n\r\ngpt-4o-transcribe\r\n--boundary--\r\n'
+)
+
+
+def _make_form_request(body: bytes, content_type: str, path: str) -> Request:
+ # real Request, not a mock: these tests exercise starlette's actual form parsing
+ scope = {
+ "type": "http",
+ "method": "POST",
+ "path": path,
+ "query_string": b"",
+ "headers": [(b"content-type", content_type.encode())],
+ "app": MagicMock(),
+ }
+
+ async def receive() -> dict:
+ return {"type": "http.request", "body": body, "more_body": False}
+
+ return Request(scope, receive)
+
+
def _make_user(auth_method: str = "personal_api_key", user_id: int = 1) -> AuthenticatedUser:
return AuthenticatedUser(
user_id=user_id,
@@ -96,6 +129,7 @@ class TestExtractEndUserIdFromBody:
request = MagicMock(spec=Request)
request.state = MagicMock()
del request.state._cached_body
+ del request.state._cached_json
async def fake_body():
return b'["not", "a", "dict"]'
@@ -104,6 +138,20 @@ class TestExtractEndUserIdFromBody:
assert await _extract_end_user_id_from_body(request) is None
+class TestGetRequestJson:
+ @pytest.mark.asyncio
+ async def test_parses_once_and_caches_the_dict(self) -> None:
+ # the access-check chain (product access, free-tier gate, end-user id) reads
+ # the body several times per request; losing the cache re-parses multi-MB
+ # completion bodies on the hot path
+ request = _make_request({"model": "gpt-4o", "messages": []})
+
+ first = await get_request_json(request)
+
+ assert first == {"model": "gpt-4o", "messages": []}
+ assert await get_request_json(request) is first
+
+
class TestGetProviderFromRequest:
@pytest.mark.asyncio
async def test_returns_provider_from_header(self) -> None:
@@ -133,8 +181,6 @@ class TestEnforceThrottles:
user_id: int = 1,
) -> ThrottleContext:
request = _make_request(body)
- request.url = MagicMock()
- request.url.path = "/openai/v1/chat/completions"
user = _make_user(auth_method=auth_method, user_id=user_id)
captured_context: ThrottleContext | None = None
@@ -238,3 +284,135 @@ class TestResolvePlanAndQuota:
quota_mock.assert_not_awaited()
assert quota_status.limited is False
+
+
+class TestGetModelFromRequest:
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "body,content_type",
+ [
+ (_TRANSCRIPTION_MULTIPART_BODY, "multipart/form-data; boundary=boundary"),
+ (b"model=gpt-4o-transcribe&language=en", "application/x-www-form-urlencoded"),
+ ],
+ )
+ async def test_reads_model_from_form_bodies(self, body: bytes, content_type: str) -> None:
+ request = _make_form_request(body, content_type, "/posthog_code/v1/audio/transcriptions")
+ assert await get_model_from_request(request) == "gpt-4o-transcribe"
+
+ @pytest.mark.asyncio
+ async def test_form_parse_leaves_the_upload_readable_for_the_endpoint(self) -> None:
+ # a parse that consumed the stream or left the upload cursor at the end
+ # would make every legitimate transcription send empty audio
+ body = (
+ b"--boundary\r\n"
+ b'Content-Disposition: form-data; name="model"\r\n\r\ngpt-4o-transcribe\r\n'
+ b"--boundary\r\n"
+ b'Content-Disposition: form-data; name="file"; filename="a.mp3"\r\n'
+ b"Content-Type: audio/mpeg\r\n\r\naudio-bytes\r\n"
+ b"--boundary--\r\n"
+ )
+ request = _make_form_request(
+ body, "multipart/form-data; boundary=boundary", "/posthog_code/v1/audio/transcriptions"
+ )
+
+ assert await get_model_from_request(request) == "gpt-4o-transcribe"
+
+ form = await request.form()
+ upload = form["file"]
+ assert not isinstance(upload, str)
+ assert await upload.read() == b"audio-bytes"
+
+
+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
+
+ monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", "true")
+ get_settings.cache_clear()
+ try:
+ request = _make_form_request(
+ _TRANSCRIPTION_MULTIPART_BODY,
+ "multipart/form-data; boundary=boundary",
+ "/posthog_code/v1/audio/transcriptions",
+ )
+ user = _make_user(auth_method="oauth_access_token", user_id=7)
+
+ runner = MagicMock()
+ runner.check = AsyncMock(return_value=ThrottleResult.allow())
+
+ with patch("llm_gateway.dependencies.ensure_costs_fresh"):
+ with pytest.raises(HTTPException) as exc_info:
+ await enforce_throttles(request=request, user=user, runner=runner)
+
+ assert exc_info.value.status_code == 403
+ assert "gpt-4o-transcribe" in exc_info.value.detail
+ finally:
+ get_settings.cache_clear()
+
+ @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
+
+ monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", "true")
+ get_settings.cache_clear()
+ try:
+ request = _make_request({"model": "claude-fable-5", "messages": []}, path="/array/v1/messages")
+ user = _make_user(auth_method="oauth_access_token", user_id=7)
+
+ runner = MagicMock()
+ runner.check = AsyncMock(return_value=ThrottleResult.allow())
+
+ with patch("llm_gateway.dependencies.ensure_costs_fresh"):
+ with pytest.raises(HTTPException) as exc_info:
+ await enforce_throttles(request=request, user=user, runner=runner)
+
+ assert exc_info.value.status_code == 403
+ assert "claude-fable-5" in exc_info.value.detail
+ finally:
+ get_settings.cache_clear()
+
+
+class TestServerCredentialRequirementWiring:
+ def _oauth_user(self, scopes: list[str]) -> AuthenticatedUser:
+ return 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,
+ )
+
+ @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
+
+ monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", "true")
+ get_settings.cache_clear()
+ try:
+ request = _make_request({"model": "claude-sonnet-5", "messages": []}, path="/signals/v1/messages")
+ with pytest.raises(HTTPException) as exc_info:
+ await enforce_product_access(request=request, user=self._oauth_user(["*"]))
+ assert exc_info.value.status_code == 403
+ assert "server-minted" in exc_info.value.detail
+ finally:
+ get_settings.cache_clear()
+
+ @pytest.mark.asyncio
+ 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
+
+ monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", "true")
+ get_settings.cache_clear()
+ try:
+ request = _make_request({"model": "claude-sonnet-5", "messages": []}, path="/signals/v1/messages")
+ user = self._oauth_user(["llm_gateway:read", "internal_run:read"])
+ assert await enforce_product_access(request=request, user=user) is user
+ finally:
+ get_settings.cache_clear()
diff --git a/services/llm-gateway/tests/test_models_api.py b/services/llm-gateway/tests/test_models_api.py
index 6c5314bd9daf..8de13d7d9130 100644
--- a/services/llm-gateway/tests/test_models_api.py
+++ b/services/llm-gateway/tests/test_models_api.py
@@ -241,3 +241,97 @@ class TestResponsesModeModels:
assert response.status_code == 200
model_ids = {m["id"] for m in response.json()["data"]}
assert "gpt-5.3-codex" in model_ids
+
+
+def _wire_authenticated_user(mock_db_pool, distinct_id: str):
+ from unittest.mock import AsyncMock
+
+ conn = AsyncMock()
+ conn.fetchrow = AsyncMock(
+ return_value={
+ "id": "key_id",
+ "user_id": 1,
+ "scopes": ["llm_gateway:read"],
+ "current_team_id": 1,
+ "distinct_id": distinct_id,
+ "is_staff": False,
+ }
+ )
+ mock_db_pool.acquire = AsyncMock(return_value=conn)
+ mock_db_pool.release = AsyncMock()
+
+
+class TestFreeTierModelListing:
+ @pytest.fixture(autouse=True)
+ def gate_enabled(self, monkeypatch: pytest.MonkeyPatch):
+ from llm_gateway.config import get_settings
+
+ monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", "true")
+ get_settings.cache_clear()
+ yield
+ get_settings.cache_clear()
+
+ def test_anonymous_caller_gets_full_unrestricted_list(self, client: TestClient):
+ # an unidentifiable caller may be a billed org; never mark for those
+ response = client.get("/posthog_code/v1/models")
+ assert response.status_code == 200
+ models = response.json()["data"]
+ assert "claude-opus-4-5" in {m["id"] for m in models}
+ assert all(m["allowed"] for m in models)
+
+ def test_unbilled_org_gets_full_list_with_premium_models_marked(self, app, mock_db_pool):
+ from unittest.mock import AsyncMock
+
+ from llm_gateway.services.quota_resolver import QuotaResourceStatus
+
+ _wire_authenticated_user(mock_db_pool, "unbilled-user")
+
+ with TestClient(app) as c:
+ c.app.state.quota_resolver.get_resource_status = AsyncMock(
+ return_value=QuotaResourceStatus(limited=False, code_usage_billing_active=False)
+ )
+ response = c.get("/posthog_code/v1/models", headers={"Authorization": "Bearer phx_unbilled_org_models"})
+
+ assert response.status_code == 200
+ body = response.json()
+ by_id = {m["id"]: m for m in body["data"]}
+ premium = by_id["claude-opus-4-5"]
+ assert premium["allowed"] is False
+ assert premium["restriction_reason"] == "paid_plan_required"
+ # exact, not subset: the default free model must survive the allowlist
+ # and the annotation, or free-tier callers have no usable model
+ assert {m["id"] for m in body["data"] if m["allowed"]} == {"@cf/zai-org/glm-5.2"}
+ # codex reads the `models` mirror; the marks must be there too
+ assert body["models"] == body["data"]
+
+ def test_billed_org_sees_full_list(self, app, mock_db_pool):
+ from unittest.mock import AsyncMock
+
+ from llm_gateway.services.quota_resolver import QuotaResourceStatus
+
+ _wire_authenticated_user(mock_db_pool, "billed-user")
+
+ with TestClient(app) as c:
+ c.app.state.quota_resolver.get_resource_status = AsyncMock(
+ return_value=QuotaResourceStatus(limited=False, code_usage_billing_active=True)
+ )
+ response = c.get("/posthog_code/v1/models", headers={"Authorization": "Bearer phx_billed_org_models"})
+
+ assert response.status_code == 200
+ models = response.json()["data"]
+ assert "claude-opus-4-5" in {m["id"] for m in models}
+ assert all(m["allowed"] for m in models)
+
+ def test_auth_resolution_failure_serves_full_unrestricted_list(self, app, mock_db_pool):
+ from unittest.mock import AsyncMock
+
+ # an auth outage must not mark a possibly-billed caller's models
+ mock_db_pool.acquire = AsyncMock(side_effect=RuntimeError("db down"))
+
+ with TestClient(app) as c:
+ response = c.get("/posthog_code/v1/models", headers={"Authorization": "Bearer phx_auth_outage_models"})
+
+ assert response.status_code == 200
+ models = response.json()["data"]
+ assert "claude-opus-4-5" in {m["id"] for m in models}
+ assert all(m["allowed"] for m in models)
diff --git a/services/llm-gateway/tests/test_openai.py b/services/llm-gateway/tests/test_openai.py
index f90e0d23d7f6..65661da794fe 100644
--- a/services/llm-gateway/tests/test_openai.py
+++ b/services/llm-gateway/tests/test_openai.py
@@ -617,3 +617,28 @@ class TestUnsupportedModelRejection:
assert response.status_code == 400
assert response.json()["error"]["code"] == "model_not_supported"
mock_completion.assert_not_called()
+
+
+class TestAudioTranscriptionsEndpoint:
+ @pytest.mark.parametrize(
+ "path",
+ ["/v1/audio/transcriptions", "/llm_gateway/v1/audio/transcriptions"],
+ )
+ @patch("llm_gateway.api.openai.litellm.atranscription")
+ def test_omitted_model_is_rejected_not_defaulted(
+ self,
+ mock_transcription: MagicMock,
+ authenticated_client: TestClient,
+ path: str,
+ ) -> None:
+ # a server-side default would route a model upstream that the access
+ # checks never saw (they run before form binding)
+ response = authenticated_client.post(
+ path,
+ files={"file": ("a.mp3", b"audio-bytes", "audio/mpeg")},
+ headers={"Authorization": "Bearer phx_test_key"},
+ )
+
+ assert response.status_code == 422
+ assert "model" in str(response.json())
+ mock_transcription.assert_not_called()
diff --git a/services/llm-gateway/tests/test_product_config.py b/services/llm-gateway/tests/test_product_config.py
index eec991cc5cb8..a658b84b30c9 100644
--- a/services/llm-gateway/tests/test_product_config.py
+++ b/services/llm-gateway/tests/test_product_config.py
@@ -9,6 +9,7 @@ from llm_gateway.products.config import (
POSTHOG_AI_DEV_APP_ID,
POSTHOG_AI_EU_APP_ID,
POSTHOG_AI_US_APP_ID,
+ POSTHOG_CODE_DEV_APP_ID,
POSTHOG_CODE_EU_APP_ID,
POSTHOG_CODE_US_APP_ID,
PRODUCT_ALIASES,
@@ -17,6 +18,7 @@ from llm_gateway.products.config import (
TWIG_US_APP_ID,
WIZARD_EU_APP_ID,
WIZARD_US_APP_ID,
+ check_free_tier_model_access,
check_product_access,
get_product_config,
resolve_product_alias,
@@ -227,7 +229,8 @@ class TestCheckProductAccess:
assert error is None
@patch(
- "llm_gateway.products.config.get_settings", return_value=MagicMock(debug=False, bedrock_region_name="us-east-1")
+ "llm_gateway.products.config.get_settings",
+ return_value=MagicMock(debug=False, bedrock_region_name="us-east-1", posthog_code_model_gate_enabled=False),
)
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
@@ -279,7 +282,8 @@ class TestCheckProductAccess:
assert "not allowed" in error
@patch(
- "llm_gateway.products.config.get_settings", return_value=MagicMock(debug=False, bedrock_region_name="us-east-1")
+ "llm_gateway.products.config.get_settings",
+ return_value=MagicMock(debug=False, bedrock_region_name="us-east-1", posthog_code_model_gate_enabled=False),
)
def test_background_agents_allows_claude_sonnet_4_6_via_bedrock_provider(self, mock_get_settings: MagicMock):
allowed, error = check_product_access(
@@ -440,3 +444,186 @@ class TestValidateProduct:
def test_resolve_product_alias_returns_input_if_not_aliased(self):
assert resolve_product_alias("wizard") == "wizard"
+
+
+class TestCheckFreeTierModelAccess:
+ @pytest.fixture(autouse=True)
+ def gate_enabled(self, monkeypatch: pytest.MonkeyPatch):
+ from llm_gateway.config import get_settings
+
+ monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", "true")
+ get_settings.cache_clear()
+ yield
+ get_settings.cache_clear()
+
+ def test_gate_disabled_by_default_allows_premium_models(self, monkeypatch: pytest.MonkeyPatch):
+ # the PR deploys inert: behavior changes only when the env flag flips
+ from llm_gateway.config import get_settings
+
+ monkeypatch.delenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", raising=False)
+ get_settings.cache_clear()
+ allowed, error = check_free_tier_model_access(
+ product="posthog_code",
+ model="claude-fable-5",
+ provider=None,
+ code_usage_billed=False,
+ usage_unlimited=False,
+ )
+ assert allowed is True
+ assert error is None
+
+ @pytest.mark.parametrize(
+ "product,model,code_usage_billed,usage_unlimited,expected_allowed",
+ [
+ # Unbilled org on the Code surface: premium blocked, open model allowed
+ ("posthog_code", "claude-fable-5", False, False, False),
+ ("posthog_code", "@cf/zai-org/glm-5.2", False, False, True),
+ # The alias routes are the same surface - a URL spelling must not bypass
+ ("array", "claude-fable-5", False, False, False),
+ ("twig", "gpt-5.5", False, False, False),
+ # Org pays for Code usage: everything stays open
+ ("posthog_code", "claude-fable-5", True, False, True),
+ # Staff bypass mirrors the cost-throttle exemption
+ ("posthog_code", "claude-fable-5", False, True, True),
+ # Other products keep their own allowlists; the gate is Code-only
+ ("llm_gateway", "claude-fable-5", False, False, True),
+ # No model in the body: nothing to gate (product allowlist still applies)
+ ("posthog_code", None, False, False, True),
+ ],
+ )
+ def test_gate_matrix(
+ self,
+ product: str,
+ model: str | None,
+ code_usage_billed: bool,
+ usage_unlimited: bool,
+ expected_allowed: bool,
+ ):
+ allowed, error = check_free_tier_model_access(
+ product=product,
+ model=model,
+ provider=None,
+ code_usage_billed=code_usage_billed,
+ usage_unlimited=usage_unlimited,
+ )
+ assert allowed is expected_allowed
+ if expected_allowed:
+ assert error is None
+ else:
+ assert model is not None and error is not None
+ assert model in error
+ assert "@cf/zai-org/glm-5.2" in error
+
+ def test_denied_model_alias_variant_is_also_denied(self):
+ # The old gate's hole: an exact-match list let date-suffixed aliases
+ # through. Prefix matching must not - but a free-listed model's own
+ # variants stay allowed.
+ allowed, _ = check_free_tier_model_access(
+ product="posthog_code",
+ model="claude-fable-5-20260301",
+ provider=None,
+ code_usage_billed=False,
+ usage_unlimited=False,
+ )
+ assert allowed is False
+ allowed, _ = check_free_tier_model_access(
+ product="posthog_code",
+ model="@cf/zai-org/glm-5.2-fp8",
+ provider=None,
+ code_usage_billed=False,
+ usage_unlimited=False,
+ )
+ assert allowed is True
+
+
+class TestServerCredentialRequirement:
+ """The internal products that share the PostHog Code OAuth app (background_agents, signals,
+ slack_app, conversations) must accept only server-minted tokens — those carrying the internal
+ `internal_run:read` marker. Otherwise a user's own Code OAuth token could route around the
+ posthog_code free-tier gate through these products to premium models."""
+
+ _MARKER_SCOPES = ["llm_gateway:read", "task:write", "internal_run:read"]
+
+ @pytest.fixture(autouse=True)
+ def gate_enabled(self, monkeypatch: pytest.MonkeyPatch):
+ from llm_gateway.config import get_settings
+
+ monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", "true")
+ get_settings.cache_clear()
+ yield
+ get_settings.cache_clear()
+
+ @pytest.mark.parametrize("product", ["background_agents", "signals", "slack_app", "conversations"])
+ def test_oauth_without_marker_is_rejected(self, product: str):
+ # a desktop Code token (wildcard scope, no internal marker); claude-sonnet-5 is in every
+ # sibling's model list, so the rejection is unambiguously the missing server credential
+ allowed, error = check_product_access(
+ product, "oauth_access_token", POSTHOG_CODE_US_APP_ID, "claude-sonnet-5", scopes=["*"]
+ )
+ assert allowed is False
+ assert error is not None and "server-minted" in error
+
+ @pytest.mark.parametrize("product", ["background_agents", "signals", "slack_app", "conversations"])
+ def test_oauth_with_marker_is_allowed(self, product: str):
+ allowed, error = check_product_access(
+ product, "oauth_access_token", POSTHOG_CODE_US_APP_ID, "claude-sonnet-5", scopes=self._MARKER_SCOPES
+ )
+ 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(
+ "signals", "personal_api_key", None, "claude-sonnet-5", scopes=["llm_gateway:read"]
+ )
+ assert allowed is True
+ assert error is None
+
+ def test_gate_disabled_leaves_sibling_access_unchanged(self, monkeypatch: pytest.MonkeyPatch):
+ # deploys inert: with the flag off, a marker-less token still reaches the siblings
+ from llm_gateway.config import get_settings
+
+ monkeypatch.delenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", raising=False)
+ get_settings.cache_clear()
+ allowed, error = check_product_access(
+ "signals", "oauth_access_token", POSTHOG_CODE_US_APP_ID, "claude-sonnet-5", scopes=["*"]
+ )
+ assert allowed is True
+ assert error is None
+
+
+_CODE_APP_IDS = frozenset({POSTHOG_CODE_DEV_APP_ID, POSTHOG_CODE_EU_APP_ID, POSTHOG_CODE_US_APP_ID})
+_CODE_APP_PRODUCTS = [
+ name
+ for name, config in PRODUCTS.items()
+ if config.allowed_application_ids and config.allowed_application_ids & _CODE_APP_IDS
+]
+
+
+class TestServerCredentialConfigInvariant:
+ # Derived from PRODUCTS rather than hand-enumerated: requires_server_credential
+ # defaults to False, so a future product added to the Code OAuth app without it
+ # would silently reopen the premium-model escape the marker closes. It must fail
+ # here instead.
+ @pytest.mark.parametrize("product", [p for p in _CODE_APP_PRODUCTS if p != "posthog_code"])
+ def test_internal_code_app_products_require_a_server_credential(self, product: str):
+ assert PRODUCTS[product].requires_server_credential, (
+ f"'{product}' accepts the PostHog Code OAuth app but doesn't require a server-minted "
+ "credential, so a user's own Code OAuth token could reach it and route around the "
+ "posthog_code free-tier model gate"
+ )
+
+ def test_posthog_code_is_the_only_code_app_product_open_to_user_tokens(self):
+ # desktop users hold marker-less Code tokens; requiring the marker on the
+ # user-facing product would lock them all out. Membership is asserted so a
+ # broken _CODE_APP_PRODUCTS derivation can't quietly hollow out this class.
+ assert "posthog_code" in _CODE_APP_PRODUCTS
+ assert PRODUCTS["posthog_code"].requires_server_credential is False