: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): trust authenticated team attribution (#84469)
Adam Bowker0bdb97d70e0f
diff --git a/services/llm-gateway/PARITY.md b/services/llm-gateway/PARITY.mdindex bcfc7470cdd4..08adadbb5554 100644--- a/services/llm-gateway/PARITY.md+++ b/services/llm-gateway/PARITY.md@@ -64,7 +64,7 @@ These are compatibility checks, not automatic blockers:| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || Authentication | `phs_` project secrets and `pha_` OAuth credentials with the literal `llm_gateway:read` scope; credential resolves a fixed team and revocation state. | `phx_` personal keys, wildcard OAuth scope handling, product-specific API key or OAuth application rules, and Desktop's request-selected project validated against OAuth scope and live organization membership. || Trusted first-party identity | No trusted product identity or product-scoped authorization boundary. | Product route selects allowlisted OAuth apps, server credential requirements, model policy, and the PostHog Desktop entitlement check on `posthog_code` (Django `has_tasks_access`, since an OAuth app allowlist alone does not prove beta membership). |-| Attribution | Distinct ID comes from `X-PostHog-Distinct-Id` or falls back to team ID. Supports trace ID, custom JSON properties, team project token, provider, usage, and cost. | OAuth user identity, body-derived OpenAI or Anthropic end-user identity, gateway-owned `$ai_product` and `$ai_billable`, per-key properties, and feature flag headers. |+| 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. |@@ -88,10 +88,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-11 against:+Last verified on 2026-08-19 against:-- `PostHog/posthog` master at `be4bd7c005a5c13980c7f89e3131cfca3d4ae501`-- `PostHog/ai-gateway` main at `107c9d62cf33d0a5a08b2ace40257f036914102a`+- `PostHog/posthog` master at `3612cfa3139901020eab974e62da0ce806e22693`+- `PostHog/ai-gateway` main at `f200a2367d5944897dbfa754127249b3fcae0da2`## Referencesdiff --git a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py b/services/llm-gateway/src/llm_gateway/callbacks/posthog.pyindex 2e2365d1f767..631c42299422 100644--- a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py+++ b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py@@ -9,7 +9,7 @@ import structlogfrom posthoganalytics import Posthogfrom posthoganalytics.ai.utils import _capture_ai_event-from llm_gateway.auth.models import resolve_distinct_id+from llm_gateway.auth.models import AuthenticatedUser, resolve_distinct_idfrom llm_gateway.callbacks.base import InstrumentedCallbackfrom llm_gateway.products.config import get_product_configfrom llm_gateway.rate_limiting.cost_refresh import normalize_metric_labels@@ -74,14 +74,15 @@ def _is_product_billable(product: str) -> bool:return config is not None and config.credit_bucket is not None-def _apply_owned_event_properties(properties: dict[str, Any], product: str, team_id: int | None) -> None:+def _apply_owned_event_properties(+ properties: dict[str, Any], product: str, auth_user: AuthenticatedUser | None+) -> None:"""Enforce gateway-owned event properties, run after caller `x-posthog-property-*` headers are merged.`ai_product`, `$ai_billable`, and `$ai_effort` are gateway-derived (effort via`ProviderConfig.extract_effort`) and must not be spoofable via headers, so we re-assert them- here and drop `$ai_effort` when the gateway found none. `team_id`, in contrast, is a- deliberate caller override (e.g. a shared-key caller attributing to a customer team); we only- fall back to the key owner's team when no override was supplied.+ here and drop `$ai_effort` when the gateway found none. OAuth requests use the authenticated+ project as `team_id`; trusted server callers can attribute usage to a customer team."""properties["ai_product"] = productproperties["$ai_billable"] = _is_product_billable(product)@@ -90,7 +91,14 @@ def _apply_owned_event_properties(properties: dict[str, Any], product: str, teamproperties["$ai_effort"] = effortelse:properties.pop("$ai_effort", None)- if team_id is not None:+ team_id = auth_user.team_id if auth_user else None+ can_override_team_id = auth_user is not None and auth_user.auth_method == "personal_api_key" and auth_user.is_staff+ if not can_override_team_id:+ if team_id is None:+ properties.pop("team_id", None)+ else:+ properties["team_id"] = team_id+ elif team_id is not None:properties.setdefault("team_id", team_id)# A header-supplied team_id arrives as a string ("42"); store it as an int so the captured# property matches the rest of the platform (the usage reporter reads it via JSONExtractInt)@@ -274,7 +282,7 @@ class PostHogCallback(InstrumentedCallback):for flag_key, variant in posthog_flags.items():properties[f"$feature/{flag_key}"] = variant- _apply_owned_event_properties(properties, product, team_id)+ _apply_owned_event_properties(properties, product, auth_user)response_cost = standard_logging_object.get("response_cost")if response_cost is not None:@@ -362,7 +370,7 @@ class PostHogCallback(InstrumentedCallback):for flag_key, variant in posthog_flags.items():properties[f"$feature/{flag_key}"] = variant- _apply_owned_event_properties(properties, product, team_id)+ _apply_owned_event_properties(properties, product, auth_user)capture_kwargs: dict[str, Any] = {"distinct_id": distinct_id,diff --git a/services/llm-gateway/tests/callbacks/test_posthog.py b/services/llm-gateway/tests/callbacks/test_posthog.pyindex d46899583c6d..6a1bb43831e5 100644--- a/services/llm-gateway/tests/callbacks/test_posthog.py+++ b/services/llm-gateway/tests/callbacks/test_posthog.py@@ -183,36 +183,53 @@ class TestPostHogCallback:assert props["$ai_effort"] == expected@pytest.mark.asyncio- async def test_on_success_header_team_id_overrides_auth_user_team(+ @pytest.mark.parametrize(+ "auth_method,is_staff,team_id,expected_team_id",+ [+ ("personal_api_key", True, 456, 999),+ ("personal_api_key", False, 456, 456),+ ("oauth_access_token", False, 456, 456),+ ("oauth_access_token", False, None, None),+ ],+ )+ async def test_on_success_team_attribution(self,callback: PostHogCallback,- auth_user: AuthenticatedUser,standard_logging_object: dict,mock_posthog_client: tuple,+ auth_method: str,+ is_staff: bool,+ team_id: int | None,+ expected_team_id: int | None,) -> None:- """A caller-supplied x-posthog-property-team_id wins over the key owner's team.-- This is how a shared-key caller (e.g. signals) attributes a generation to the- customer team rather than the key owner's team that the usage reporter reads.- """_, mock_client = mock_posthog_clientkwargs = {"standard_logging_object": standard_logging_object, "litellm_params": {}}+ auth_user = AuthenticatedUser(+ user_id=123,+ team_id=team_id,+ auth_method=auth_method,+ distinct_id="user-distinct-id-123",+ is_staff=is_staff,+ )with (patch("llm_gateway.callbacks.posthog.get_auth_user", return_value=auth_user),patch("llm_gateway.callbacks.posthog.get_product", return_value="signals"),- # headers arrive as strings — this is the realistic x-posthog-property-team_id pathpatch("llm_gateway.callbacks.posthog.get_posthog_properties", return_value={"team_id": "999"}),):await callback._on_success(kwargs, None, 0.0, 1.0, end_user_id=None)- call_kwargs = mock_client.capture.call_args.kwargs- props = call_kwargs["properties"]- # header-supplied customer team wins over auth_user.team_id (456), stored as an int- assert props["team_id"] == 999+ call_kwargs = mock_client.capture.call_args.kwargs+ props = mock_client.capture.call_args.kwargs["properties"]+ if expected_team_id is None:+ assert "team_id" not in props+ else:+ assert props["team_id"] == expected_team_idassert isinstance(props["team_id"], int)- # the analytics project the event lands in still follows the authenticated team- assert call_kwargs["groups"] == {"instance": "https://us.posthog.com", "project": 456}+ expected_groups: dict[str, str | int] = {"instance": "https://us.posthog.com"}+ if team_id is not None:+ expected_groups["project"] = team_id+ assert call_kwargs["groups"] == expected_groups@pytest.mark.asyncioasync def test_on_success_invalid_header_team_id_falls_back_to_auth_team(