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(flags): honor POSTHOG_SELF_TEAM_ID for the browser flag token (#88394)

Ben White08c24a137f24
diff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.py
index a5cc39bff843..4f215b3e3c6c 100644
--- a/posthog/test/test_utils.py
+++ b/posthog/test/test_utils.py
@@ -1415,6 +1415,12 @@ class TestSelfCaptureBrowserFlagToken(TestCase):
# is the first one. Cascade deletes roll back with the test transaction.
User.objects.all().delete()
Organization.objects.all().delete()
+ # POSTHOG_SELF_TEAM_ID steers the browser token as well as the flag provider, so set the
+ # environment per test instead of inheriting whatever the ambient one holds.
+ env_patch = patch.dict(os.environ, {}, clear=False)
+ env_patch.start()
+ self.addCleanup(env_patch.stop)
+ os.environ.pop("POSTHOG_SELF_TEAM_ID", None)
@override_settings(SELF_CAPTURE=True, E2E_TESTING=False)
def test_browser_token_uses_dogfood_flags_team_not_self_capture_team(self):
@@ -1439,6 +1445,40 @@ class TestSelfCaptureBrowserFlagToken(TestCase):
assert context["js_posthog_api_key"] == first_team.api_token
assert first_team.api_token != recent_team.api_token
+ @override_settings(SELF_CAPTURE=True, E2E_TESTING=False)
+ def test_browser_token_honors_explicit_self_team_id(self):
+ # A deploy that pins POSTHOG_SELF_TEAM_ID bootstraps flags from that team, so the browser
+ # token has to follow the pin. Reading the first team by PK instead hands posthog-js the
+ # token of whichever team is oldest, which on a long-lived deploy is a seed team that holds
+ # no internal flag definitions.
+ organization = Organization.objects.create(name="Org")
+ first_team = Team.objects.create(organization=organization, name="First")
+ pinned_team = Team.objects.create(organization=organization, name="Pinned")
+
+ request = RequestFactory().get("/?no-preloaded-app-context=1")
+ request.user = AnonymousUser()
+
+ os.environ["POSTHOG_SELF_TEAM_ID"] = str(pinned_team.id)
+ context = get_context_for_template("head.html", request)
+
+ assert context["js_posthog_api_key"] == pinned_team.api_token
+ assert pinned_team.api_token != first_team.api_token
+
+ @override_settings(SELF_CAPTURE=True, E2E_TESTING=False)
+ def test_browser_token_unset_when_pinned_team_is_absent(self):
+ # The provider still pins flag definitions to the missing id, so falling back to another
+ # team's token would recreate the mismatch the pin exists to remove.
+ organization = Organization.objects.create(name="Org")
+ Team.objects.create(organization=organization, name="First")
+
+ request = RequestFactory().get("/?no-preloaded-app-context=1")
+ request.user = AnonymousUser()
+
+ os.environ["POSTHOG_SELF_TEAM_ID"] = "987654321"
+ context = get_context_for_template("head.html", request)
+
+ assert context.get("js_posthog_api_key") is None
+
VALID_PRELOAD_MANIFEST = {
"css": "static/index-ABC123.css",
diff --git a/posthog/utils.py b/posthog/utils.py
index fcc9d5b1eb07..f7770ef03032 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -544,16 +544,19 @@ def _build_template_context(
elif settings.SELF_CAPTURE:
# posthog-js uses this token to evaluate PostHog's own gating flags, so it must point at the
- # team those flags are synced to — the dogfood-flags team (first team by PK), the same team
- # the server-side bootstrap evaluates against via _build_flag_provider(). Do NOT use the
- # self-capture team here (posthoganalytics.api_key = most-recently-active user's current_team):
- # it drifts onto demo teams that hold no internal flags, so flags load from the bootstrap and
- # then vanish the moment posthog-js reloads them against that team.
- dogfood_team = resolve_dogfood_flags_team()
- if dogfood_team is not None:
- context["js_posthog_api_key"] = dogfood_team.api_token
+ # team the server-side bootstrap evaluates against via _build_flag_provider(). Both resolve
+ # through resolve_self_flags_team() for that reason: the POSTHOG_SELF_TEAM_ID override when
+ # it is set, else the dogfood-flags team that `sync_feature_flags_from_api` writes to. Do NOT
+ # use the self-capture team here (posthoganalytics.api_key = most-recently-active user's
+ # current_team): it drifts onto demo teams that hold no internal flags, so flags load from
+ # the bootstrap and then vanish the moment posthog-js reloads them against that team.
+ self_flags_team = resolve_self_flags_team()
+ if self_flags_team is not None:
+ context["js_posthog_api_key"] = self_flags_team.api_token
context["js_posthog_host"] = "" # Becomes location.origin in the frontend
- elif posthoganalytics.api_key:
+ elif get_explicit_self_team_id() is None and posthoganalytics.api_key:
+ # Only reachable without an override. A pinned team that does not exist leaves the token
+ # unset, because sending any other team's token is the mismatch described above.
context["js_posthog_api_key"] = posthoganalytics.api_key
context["js_posthog_host"] = "" # Becomes location.origin in the frontend
else:
@@ -838,6 +841,39 @@ def get_dogfood_flags_team_id() -> Optional[int]:
return team.id if team is not None else None
+def get_explicit_self_team_id() -> Optional[int]:
+ """The `POSTHOG_SELF_TEAM_ID` operator override, or None when it is unset.
+
+ Truthiness, not `is not None`: an empty env var means "unset" and must fall through to the
+ defaults, not crash on int("").
+ """
+ raw_team_id = os.environ.get("POSTHOG_SELF_TEAM_ID")
+ return int(raw_team_id) if raw_team_id else None
+
+
+def resolve_self_flags_team() -> Optional["Team"]:
+ """Resolve the team whose flag definitions represent this instance, honoring the override.
+
+ This must stay in lockstep with `_build_flag_provider()`, which pins the same team for the
+ server-side bootstrap. posthog-js evaluates PostHog's own gating flags with this team's token,
+ so when the two resolve to different teams the browser reloads flags against a team that holds
+ no definitions for them.
+
+ When the override names a team that does not exist, return None rather than another team: the
+ provider still pins definitions to that id, so substituting a different team here reintroduces
+ the mismatch above.
+ """
+ Team = apps.get_model("posthog", "Team")
+ explicit_team_id = get_explicit_self_team_id()
+ if explicit_team_id is None:
+ return resolve_dogfood_flags_team()
+ try:
+ return Team.objects.filter(pk=explicit_team_id).first()
+ except ProgrammingError:
+ # Table absent before migrations have run.
+ return None
+
+
def _build_flag_provider() -> "HyperCacheFlagProvider":
"""Construct the HyperCache flag-definition provider for this deploy.
@@ -852,12 +888,11 @@ def _build_flag_provider() -> "HyperCacheFlagProvider":
HyperCacheFlagProvider,
)
- explicit_team_id = os.environ.get("POSTHOG_SELF_TEAM_ID")
- if explicit_team_id:
- # Operator override: pin the flag-definitions team explicitly.
- # Truthiness, not `is not None`: an empty env var means "unset" and must
- # fall through to the defaults below, not crash on int("").
- return HyperCacheFlagProvider.for_static_team(int(explicit_team_id))
+ explicit_team_id = get_explicit_self_team_id()
+ if explicit_team_id is not None:
+ # Operator override: pin the flag-definitions team explicitly. The browser token resolves
+ # through the same override in resolve_self_flags_team(), so both stay on this team.
+ return HyperCacheFlagProvider.for_static_team(explicit_team_id)
if settings.SELF_CAPTURE and not settings.E2E_TESTING:
# Local/self-hosted: read flag definitions from the dogfood team
# (project.teams.first()), resolved lazily once teams/migrations exist.