: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(llm-gateway): reject expired personal api keys (#122119)
Alex Lider04ea96a25c76
diff --git a/services/llm-gateway/PARITY.md b/services/llm-gateway/PARITY.mdindex d8231b999ea1..b419ba99c94b 100644--- a/services/llm-gateway/PARITY.md+++ b/services/llm-gateway/PARITY.md@@ -79,20 +79,20 @@ These are compatibility checks, not automatic blockers:## Parity map-| Contract | Go gateway today | Python-only behavior that can block migration |-| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Authentication | `phs_` project secrets and `pha_` OAuth credentials require `llm_gateway:read`. A `pha_` credential is also rejected when its user has `is_email_verified = false`; `NULL` (legacy accounts) and `true` pass. Standard credentials can mint capped and revocable `phe_` tokens. | `phx_` personal keys (rejected on the same `is_email_verified = false` rule, without the `email-verification-disabled` incident flag bypass that Django honors), 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 | Scoped tokens pin product, user, and obo attribution at mint. Standard credential headers remain caller-controlled and do not authorize a product. | Product routes select allowlisted OAuth apps, server credential requirements, model policy, and Django product policy. Django also decides which callers may receive a product-scoped credential. |-| Attribution | Distinct ID comes from `X-PostHog-Distinct-Id` or falls back to a namespaced team identity. Product, user, and obo attribution land on events and ledger entries with provenance. | OAuth user identity, ACL-resolved OAuth team attribution, staff-owned personal-key customer-team overrides, body-derived end-user identity, gateway-owned `$ai_billable`, per-key properties, and feature flag headers. |-| Billing and limits | Wallet reservation and settlement, soft attribution budgets, a hard team cap, per-token caps, idempotency, balance and usage reads, and front-line rate limits. | Plans, quota buckets, product-specific free-model policy, unbilled products, product usage status, and Django provenance rules that decide which cap applies. |-| 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, per-model access flags with caller-filtered listings, 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 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. Callers on this gateway send these, and litellm otherwise raises an error with no status code that the handler reports as 500. |+| Contract | Go gateway today | Python-only behavior that can block migration |+| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Authentication | `phs_` project secrets and `pha_` OAuth credentials require `llm_gateway:read`. A `pha_` credential is also rejected when its user has `is_email_verified = false`; `NULL` (legacy accounts) and `true` pass. Standard credentials can mint capped and revocable `phe_` tokens. | `phx_` personal keys (rejected once their `expires_at` passes and on the same `is_email_verified = false` rule, without the `email-verification-disabled` incident flag bypass that Django honors), 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 | Scoped tokens pin product, user, and obo attribution at mint. Standard credential headers remain caller-controlled and do not authorize a product. | Product routes select allowlisted OAuth apps, server credential requirements, model policy, and Django product policy. Django also decides which callers may receive a product-scoped credential. |+| Attribution | Distinct ID comes from `X-PostHog-Distinct-Id` or falls back to a namespaced team identity. Product, user, and obo attribution land on events and ledger entries with provenance. | OAuth user identity, ACL-resolved OAuth team attribution, staff-owned personal-key customer-team overrides, body-derived end-user identity, gateway-owned `$ai_billable`, per-key properties, and feature flag headers. |+| Billing and limits | Wallet reservation and settlement, soft attribution budgets, a hard team cap, per-token caps, idempotency, balance and usage reads, and front-line rate limits. | Plans, quota buckets, product-specific free-model policy, unbilled products, product usage status, and Django provenance rules that decide which cap applies. |+| 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, per-model access flags with caller-filtered listings, 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 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. Callers on this gateway send these, and litellm otherwise raises an error with no status code that the handler reports as 500. |## Migration checklistdiff --git a/services/llm-gateway/src/llm_gateway/auth/authenticators.py b/services/llm-gateway/src/llm_gateway/auth/authenticators.pyindex ffff2ef23de6..217f204c32a5 100644--- a/services/llm-gateway/src/llm_gateway/auth/authenticators.py+++ b/services/llm-gateway/src/llm_gateway/auth/authenticators.py@@ -62,7 +62,8 @@ class PersonalApiKeyAuthenticator(Authenticator):async with acquire_connection(pool) as conn:row = await conn.fetchrow("""- SELECT pak.id, pak.user_id, pak.scopes, u.current_team_id, u.distinct_id, u.is_staff+ SELECT pak.id, pak.user_id, pak.scopes, pak.expires_at,+ u.current_team_id, u.distinct_id, u.is_staffFROM posthog_personalapikey pakJOIN posthog_user u ON pak.user_id = u.idWHERE pak.secure_value = $1 AND u.is_active = true@@ -75,6 +76,11 @@ class PersonalApiKeyAuthenticator(Authenticator):if not row:return None+ # Same boundary as Django's PersonalAPIKey.is_expired: the expiry instant itself is expired.+ expires_at: datetime | None = row.get("expires_at")+ if expires_at and expires_at <= datetime.now(UTC):+ return None+scopes = row["scopes"] or []if not has_required_scope(scopes):return None@@ -85,6 +91,8 @@ class PersonalApiKeyAuthenticator(Authenticator):auth_method=self.auth_type,distinct_id=row["distinct_id"],scopes=scopes,+ # AuthCache caps the entry's TTL at token_expires_at, so a cached hit cannot outlive the key.+ token_expires_at=expires_at,is_staff=row["is_staff"],)diff --git a/services/llm-gateway/tests/test_auth.py b/services/llm-gateway/tests/test_auth.pyindex e1e771687b1d..85b1a5551244 100644--- a/services/llm-gateway/tests/test_auth.py+++ b/services/llm-gateway/tests/test_auth.py@@ -686,8 +686,15 @@ class TestPersonalApiKeyAuthenticator:assert authenticator.matches("random_token") is False@pytest.mark.asyncio+ @pytest.mark.parametrize(+ "expires_at",+ [+ pytest.param(None, id="never_expires"),+ pytest.param(datetime.now(UTC) + timedelta(days=1), id="expires_tomorrow"),+ ],+ )async def test_valid_key_returns_authenticated_user(- self, authenticator: PersonalApiKeyAuthenticator, mock_pool: MagicMock+ self, authenticator: PersonalApiKeyAuthenticator, mock_pool: MagicMock, expires_at: datetime | None) -> None:conn = mock_pool.acquire.return_valueconn.fetchrow = AsyncMock(@@ -698,6 +705,7 @@ class TestPersonalApiKeyAuthenticator:"current_team_id": 456,"distinct_id": "test-distinct-id","is_staff": False,+ "expires_at": expires_at,})@@ -709,6 +717,7 @@ class TestPersonalApiKeyAuthenticator:assert result.team_id == 456assert result.auth_method == "personal_api_key"assert result.is_staff is False+ assert result.token_expires_at == expires_at@pytest.mark.asyncioasync def test_query_requires_verified_email(@@ -744,6 +753,16 @@ class TestPersonalApiKeyAuthenticator:{"id": "k4", "user_id": 101, "scopes": ["*"], "current_team_id": 201},id="wildcard_scope_rejected",),+ pytest.param(+ {+ "id": "k5",+ "user_id": 102,+ "scopes": ["llm_gateway:read"],+ "current_team_id": 202,+ "expires_at": datetime.now(UTC) - timedelta(minutes=1),+ },+ id="expired_key",+ ),],)async def test_invalid_keys_return_none(