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(feature-flags): mark internal Django callers as non-billable (#57884)

Dylan Martin073344de6d0e
diff --git a/posthog/api/feature_flag.py b/posthog/api/feature_flag.py
index e3ad2c6e4b92..6a3819949ea6 100644
--- a/posthog/api/feature_flag.py
+++ b/posthog/api/feature_flag.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-import os
import re
import copy
import json
@@ -2760,10 +2759,13 @@ class FeatureFlagViewSet(
if not distinct_id:
raise exceptions.ValidationError("User distinct_id is required")
+ # Authenticated Django UI handler (the flags list in the app), not customer SDK
+ # traffic. Pass the internal token so the call bypasses per-team billing.
result = get_flags_from_service(
token=self.team.api_token,
distinct_id=distinct_id,
groups=groups,
+ internal_request_token=settings.INTERNAL_REQUEST_TOKEN,
)
# Result from Rust service is always a dictionary. Parse it to get the flags data.
@@ -3504,11 +3506,14 @@ class FeatureFlagViewSet(
if isinstance(groups, str):
groups = json.loads(groups) if groups else {}
+ # PostHog UI debug endpoint, not customer SDK traffic. Pass the internal
+ # token so the call bypasses per-team billing.
result = get_flags_from_service(
token=self.team.api_token,
distinct_id=distinct_id,
groups=groups,
evaluation_runtime="all",
+ internal_request_token=settings.INTERNAL_REQUEST_TOKEN,
)
# Result from Rust service is always a dictionary with a "flags" key. Parse it to get the flags data.
@@ -3789,7 +3794,7 @@ class FeatureFlagViewSet(
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
- internal_token = os.getenv("INTERNAL_REQUEST_TOKEN")
+ internal_token = settings.INTERNAL_REQUEST_TOKEN
if not internal_token:
return Response(
{"error": "Internal request token not configured"},
diff --git a/posthog/api/test/test_feature_flag.py b/posthog/api/test/test_feature_flag.py
index dffe0dae81e1..bb69c4752dad 100644
--- a/posthog/api/test/test_feature_flag.py
+++ b/posthog/api/test/test_feature_flag.py
@@ -1,4 +1,3 @@
-import os
import json
from datetime import UTC, datetime, timedelta
from typing import Any, Optional, cast
@@ -17,6 +16,7 @@ from posthog.test.base import (
from unittest.mock import ANY, patch
from django.core.cache import cache
+from django.test import override_settings
from django.utils.timezone import now
from parameterized import parameterized
@@ -12935,7 +12935,7 @@ class TestFeatureFlagVersions(APIBaseTest):
class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):
@patch("posthog.api.feature_flag.get_flags_from_service")
@patch("posthog.api.feature_flag.get_person_and_distinct_ids_for_identifier")
- @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ @override_settings(INTERNAL_REQUEST_TOKEN="test-token")
def test_test_evaluation_happy_path(self, mock_get_person, mock_get_flags):
"""Test successful evaluation of a feature flag."""
flag = FeatureFlag.objects.create(
@@ -12992,7 +12992,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):
@patch("posthog.api.feature_flag.get_flags_from_service")
@patch("posthog.api.feature_flag.get_person_and_distinct_ids_for_identifier")
- @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ @override_settings(INTERNAL_REQUEST_TOKEN="test-token")
def test_test_evaluation_with_person_id_uses_smallest_distinct_id(self, mock_get_person, mock_get_flags):
"""When the caller passes person_id (no distinct_id), bucketing must
pick the lexicographically smallest distinct_id so two calls with the
@@ -13032,7 +13032,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):
self.assertIsNone(response.json()["evaluation_distinct_id"])
@patch("posthog.api.feature_flag.get_flags_from_service")
- @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ @override_settings(INTERNAL_REQUEST_TOKEN="test-token")
def test_test_evaluation_with_timestamp(self, mock_get_flags):
"""Historical evaluation must drive the Rust call with reconstructed
person properties + override definitions, not the live flag's data."""
@@ -13132,23 +13132,23 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(response.json()["detail"], "Person not found for distinct_id: nonexistent-user")
@patch("posthog.api.feature_flag.get_flags_from_service")
+ @override_settings(INTERNAL_REQUEST_TOKEN="")
def test_test_evaluation_missing_internal_token_error(self, mock_get_flags):
"""Test 500 when INTERNAL_REQUEST_TOKEN is not set."""
flag = FeatureFlag.objects.create(team=self.team, key="test-flag")
Person.objects.create(team=self.team, distinct_ids=["test-user"])
- with patch("posthog.api.feature_flag.os.getenv", return_value=None):
- response = self.client.post(
- f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",
- {"distinct_id": "test-user"},
- format="json",
- )
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",
+ {"distinct_id": "test-user"},
+ format="json",
+ )
self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)
self.assertEqual(response.json()["error"], "Internal request token not configured")
@patch("posthog.api.feature_flag.get_flags_from_service")
- @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ @override_settings(INTERNAL_REQUEST_TOKEN="test-token")
def test_test_evaluation_historical_missing_conditions_502(self, mock_get_flags):
"""Test 502 when historical evaluation returns no conditions (misconfigured token)."""
flag = FeatureFlag.objects.create(team=self.team, key="test-flag")
@@ -13183,7 +13183,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(response.json()["error"], "Historical evaluation unavailable. Check service configuration.")
@patch("posthog.api.feature_flag.get_flags_from_service")
- @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ @override_settings(INTERNAL_REQUEST_TOKEN="test-token")
def test_test_evaluation_current_missing_conditions_200(self, mock_get_flags):
"""Test 200 when current evaluation returns no conditions (no 502 for current evaluation)."""
flag = FeatureFlag.objects.create(team=self.team, key="test-flag")
@@ -13233,7 +13233,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(response.json()["error"], "Failed to build person properties at specified timestamp.")
@patch("posthog.api.feature_flag.get_flags_from_service")
- @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ @override_settings(INTERNAL_REQUEST_TOKEN="test-token")
def test_test_evaluation_filters_person_properties(self, mock_get_flags):
"""Test that person_properties are filtered to only flag-referenced keys."""
flag = FeatureFlag.objects.create(
@@ -13281,7 +13281,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(data["person_properties"], {"email": "[email protected]"})
@patch("posthog.api.feature_flag.get_flags_from_service")
- @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ @override_settings(INTERNAL_REQUEST_TOKEN="test-token")
def test_test_evaluation_unexpected_response_type(self, mock_get_flags):
"""Test 502 when flag service returns unexpected response format."""
flag = FeatureFlag.objects.create(team=self.team, key="test-flag")
@@ -13334,7 +13334,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(response.status_code, 400)
@patch("posthog.api.feature_flag.get_flags_from_service")
- @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ @override_settings(INTERNAL_REQUEST_TOKEN="test-token")
def test_test_evaluation_build_properties_value_error_no_leak(self, mock_get_flags):
"""Test that ValueError from build_person_properties_at_time doesn't leak sensitive information."""
mock_get_flags.return_value = {
@@ -13388,7 +13388,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):
mock_build_props.assert_called_once()
@patch("posthog.api.feature_flag.get_flags_from_service")
- @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ @override_settings(INTERNAL_REQUEST_TOKEN="test-token")
def test_test_evaluation_reconstruct_flag_value_error_no_leak(self, mock_get_flags):
"""Test that ValueError from reconstruct_flag_at_timestamp doesn't leak sensitive information."""
flag = FeatureFlag.objects.create(
@@ -13455,6 +13455,29 @@ class TestFeatureFlagEvaluationReasons(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(mock_get_flags.call_args.kwargs["evaluation_runtime"], "all")
+ @parameterized.expand(
+ [
+ ("evaluation_reasons", "evaluation_reasons/", {"distinct_id": "user-1"}, False),
+ ("my_flags", "my_flags/", {}, True),
+ ]
+ )
+ @patch("posthog.api.feature_flag.get_flags_from_service")
+ def test_internal_handler_forwards_internal_request_token(
+ self, _name, endpoint, params, needs_flag, mock_get_flags
+ ):
+ """The in-app Django handlers (my_flags, evaluation_reasons) are not
+ customer SDK traffic — they must forward INTERNAL_REQUEST_TOKEN so the
+ Rust service skips the per-team billing limiter."""
+ if needs_flag:
+ FeatureFlag.objects.create(team=self.team, key="my-flag", created_by=self.user)
+ mock_get_flags.return_value = {"flags": {}}
+
+ with self.settings(INTERNAL_REQUEST_TOKEN="test-internal-token"):
+ response = self.client.get(f"/api/projects/{self.team.pk}/feature_flags/{endpoint}", params)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(mock_get_flags.call_args.kwargs["internal_request_token"], "test-internal-token")
+
@parameterized.expand(
[
("all",),
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.py
index c52c3c766643..b77fc4a59bbe 100644
--- a/posthog/api/test/test_user.py
+++ b/posthog/api/test/test_user.py
@@ -1495,6 +1495,23 @@ class TestUserAPI(APIBaseTest):
self.assertIn("test-flag-1", cached_data["feature_flags"])
self.assertIn("test-flag-2", cached_data["feature_flags"])
+ @patch("posthog.api.user.get_flags_from_service")
+ def test_prepare_toolbar_preloaded_flags_passes_internal_request_token(self, mock_get_flags):
+ """The toolbar prep handler is internal PostHog traffic, not customer SDK
+ traffic — it must forward INTERNAL_REQUEST_TOKEN so the Rust service skips
+ the per-team billing limiter."""
+ mock_get_flags.return_value = {"flags": {}}
+
+ with self.settings(INTERNAL_REQUEST_TOKEN="test-internal-token"):
+ response = self.client.post(
+ "/api/user/prepare_toolbar_preloaded_flags/",
+ {"distinct_id": "user123"},
+ content_type="application/json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(mock_get_flags.call_args.kwargs["internal_request_token"], "test-internal-token")
+
def test_get_toolbar_preloaded_flags_retrieves_from_cache(self):
"""Test that get_toolbar_preloaded_flags retrieves flags from cache"""
from django.core.cache import cache
diff --git a/posthog/api/user.py b/posthog/api/user.py
index 5bc437745e37..38423b4912fe 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -1435,11 +1435,14 @@ def prepare_toolbar_preloaded_flags(request):
logger.warning("[Toolbar Flags] No team found")
return JsonResponse({"error": "No team found"}, status=400)
- # Use Rust flags service
+ # Use Rust flags service. Pass the internal token so this Django -> Rust
+ # call bypasses the team's billing limiter and isn't counted as customer
+ # SDK traffic — the toolbar launch is internal PostHog UI, not an SDK call.
result = get_flags_from_service(
token=team.api_token,
distinct_id=distinct_id,
groups={},
+ internal_request_token=settings.INTERNAL_REQUEST_TOKEN,
)
flags = {
flag_key: (
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index d4e4154f5c0a..097ec9433ed2 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -509,6 +509,12 @@ FLAGS_REDIS_URL = os.getenv("FLAGS_REDIS_URL", None)
# This is used to proxy flag evaluation requests to the Rust feature flags service
FEATURE_FLAGS_SERVICE_URL = os.getenv("FEATURE_FLAGS_SERVICE_URL", "http://localhost:3001")
+# Bearer token for marking Django -> Rust /flags calls as internal (non-billable).
+# When set, internal Django callers (toolbar prep, my_flags, evaluation_reasons) pass this
+# as `Authorization: Bearer …` so the Rust service skips per-team billing and quota limits.
+# Must match `INTERNAL_REQUEST_TOKEN` in the feature-flags service env.
+INTERNAL_REQUEST_TOKEN = os.getenv("INTERNAL_REQUEST_TOKEN", "")
+
FLAGS_CACHE_TTL = int(os.getenv("FLAGS_CACHE_TTL", str(60 * 60 * 24 * 7))) # 7 days
FLAGS_CACHE_MISS_TTL = int(os.getenv("FLAGS_CACHE_MISS_TTL", str(60 * 60 * 24))) # 1 day
LLM_PROMPTS_CACHE_TTL = int(os.getenv("LLM_PROMPTS_CACHE_TTL", str(60 * 60 * 24))) # 1 day