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(auth): add legacy secret token kill switch (#116448)

Patricio81208e060da2
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.py
index 8add530d90b2..35f4904ce8de 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -2501,6 +2501,16 @@ class TestTeamSecretTokenAuthentication(APIBaseTest):
access_method=AccessMethod.TEAM_SECRET_TOKEN,
)
+ @override_settings(ACCEPT_TEAM_SECRET_TOKENS=False)
+ def test_authenticate_returns_none_when_legacy_tokens_switched_off(self) -> None:
+ wsgi_request = self.factory.get(
+ "/",
+ headers={"AUTHORIZATION": f"Bearer {self.team.secret_api_token}"},
+ )
+ result = TeamSecretTokenAuthentication().authenticate(Request(wsgi_request))
+
+ self.assertIsNone(result)
+
def test_authenticate_with_valid_secret_api_key_in_body_not_supported(self):
# Body tokens were removed after the audit in #66176: even a valid token must not authenticate.
wsgi_request = self.factory.post(
diff --git a/posthog/auth.py b/posthog/auth.py
index ae44f27eafbb..004012614069 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -464,6 +464,9 @@ class TeamSecretTokenAuthentication(ActivityCredentialMixin, authentication.Base
activity_credential_type = "team_secret_token"
def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
+ if not settings.ACCEPT_TEAM_SECRET_TOKENS:
+ return None
+
secret_api_token = _extract_phs_token(request)
if not secret_api_token:
@@ -535,9 +538,10 @@ class ProjectSecretAPIKeyAuthentication(ActivityCredentialMixin, authentication.
if psak is None:
return None
- if self.defer_migrated_team_tokens and token in (
- psak.team.secret_api_token,
- psak.team.secret_api_token_backup,
+ if (
+ self.defer_migrated_team_tokens
+ and settings.ACCEPT_TEAM_SECRET_TOKENS
+ and token in (psak.team.secret_api_token, psak.team.secret_api_token_backup)
):
return None
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 2a43bd03877a..8cf38cddc431 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -352,6 +352,13 @@ SOCIAL_AUTH_GITLAB_API_URL: str = os.getenv("SOCIAL_AUTH_GITLAB_API_URL", "https
LICENSE_SECRET_KEY = os.getenv("LICENSE_SECRET_KEY", "license-so-secret")
+# Kill switch for legacy Team.secret_api_token auth (#66179). When False, the legacy
+# verifiers (TeamSecretTokenAuthentication, the conversations/customer-analytics external
+# team-token branches, the widget identity-verification legacy fallback) all go inert, and
+# ProjectSecretAPIKeyAuthentication stops deferring tokens that match a team's legacy
+# token — migrated tokens then authenticate via their backfilled PSAK mirror rows.
+ACCEPT_TEAM_SECRET_TOKENS = get_from_env("ACCEPT_TEAM_SECRET_TOKENS", True, type_cast=str_to_bool)
+
# Cookie age in seconds (default 2 weeks) - these are the standard defaults for Django but having it here to be explicit
SESSION_ENGINE = "posthog.session.backend"
SESSION_COOKIE_AGE = get_from_env("SESSION_COOKIE_AGE", 60 * 60 * 24 * 14, type_cast=int)
diff --git a/products/conversations/backend/api/external.py b/products/conversations/backend/api/external.py
index b243ec5920a7..c3de7d21c904 100644
--- a/products/conversations/backend/api/external.py
+++ b/products/conversations/backend/api/external.py
@@ -12,6 +12,7 @@ route, api/internal.py). Both routes share the handlers in api/ticket_actions.py
import hashlib
from typing import Any, cast
+from django.conf import settings
from django.db.models import Q
from django.http import HttpRequest
@@ -94,6 +95,11 @@ def _authenticate_psak_team(request: Request) -> tuple[Team, None] | tuple[None,
def _authenticate_team(request: Request) -> tuple[Team, None] | tuple[None, Response]:
"""Extract Bearer token from Authorization header and validate against team."""
+ # Kill switch (#66179): with legacy tokens off, migrated tokens authenticate as PSAKs
+ # (the deferral above also goes inert) and never reach here; the rest get a plain 401.
+ if not settings.ACCEPT_TEAM_SECRET_TOKENS:
+ return None, Response({"error": "Missing or invalid API key"}, status=status.HTTP_401_UNAUTHORIZED)
+
auth_header = request.headers.get("Authorization", "")
if not auth_header.startswith("Bearer "):
return None, Response({"error": "Missing or invalid Authorization header"}, status=status.HTTP_401_UNAUTHORIZED)
@@ -112,6 +118,12 @@ def _authenticate_team(request: Request) -> tuple[Team, None] | tuple[None, Resp
except (Team.DoesNotExist, Team.MultipleObjectsReturned):
return None, Response({"error": "Invalid API key"}, status=status.HTTP_401_UNAUTHORIZED)
+ # Same 401 as an unknown token: a valid secret token must not outlive its
+ # deactivated or deletion-pending organization.
+ organization = team.organization
+ if not organization.is_active or organization.is_pending_deletion:
+ return None, Response({"error": "Invalid API key"}, status=status.HTTP_401_UNAUTHORIZED)
+
TICKET_ACTION_AUTH_COUNTER.labels(auth_method="secret_api_token", http_method=(request.method or "").lower()).inc()
LEGACY_TICKET_AUTH_BY_TEAM_COUNTER.labels(team_id=str(team.id)).inc()
return team, None
diff --git a/products/conversations/backend/api/tests/test_external.py b/products/conversations/backend/api/tests/test_external.py
index 072adc0a19df..fb1c9d33c3f8 100644
--- a/products/conversations/backend/api/tests/test_external.py
+++ b/products/conversations/backend/api/tests/test_external.py
@@ -4,7 +4,7 @@ from datetime import timedelta
from posthog.test.base import BaseTest
from django.db import connection
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, override_settings
from django.test.utils import CaptureQueriesContext
from django.utils import timezone
@@ -86,6 +86,45 @@ class TestExternalTicketAPI(BaseTest):
self.ticket.refresh_from_db()
self.assertEqual(self.ticket.status, Status.RESOLVED)
+ @override_settings(ACCEPT_TEAM_SECRET_TOKENS=False)
+ def test_kill_switch_off_migrated_token_flows_through_its_psak_row(self) -> None:
+ # With the switch off (#66179), the legacy string authenticates through its PSAK
+ # row, so GET still returns 200 and PATCH returns 403.
+ token = self.team.secret_api_token
+ create_project_secret_api_key(
+ self.team,
+ label="Migrated legacy secret API key",
+ scopes=["feature_flag:read", "support_ticket:read"],
+ value=token,
+ )
+
+ response = self.client.get(self.url, **self._auth_headers(token))
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ response = self.client.patch(
+ self.url, {"status": "resolved"}, content_type="application/json", **self._auth_headers(token)
+ )
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ @parameterized.expand(
+ [
+ ("organization_deactivated", {"is_active": False}),
+ ("organization_pending_deletion", {"is_pending_deletion": True}),
+ ]
+ )
+ def test_legacy_token_is_rejected_when_the_organization_is_blocked(self, _name: str, changes: dict) -> None:
+ for field, value in changes.items():
+ setattr(self.organization, field, value)
+ self.organization.save()
+
+ response = self.client.get(self.url, **self._auth_headers())
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+
+ @override_settings(ACCEPT_TEAM_SECRET_TOKENS=False)
+ def test_kill_switch_off_rejects_legacy_token_without_mirror_row(self) -> None:
+ response = self.client.get(self.url, **self._auth_headers())
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+
@parameterized.expand(
[
("conversations_disabled", {"team": {"conversations_enabled": False}}),
diff --git a/products/conversations/backend/api/tests/test_widget.py b/products/conversations/backend/api/tests/test_widget.py
index b33f1785e028..82a39b7938dd 100644
--- a/products/conversations/backend/api/tests/test_widget.py
+++ b/products/conversations/backend/api/tests/test_widget.py
@@ -6,7 +6,7 @@ from posthog.test.base import BaseTest
from unittest.mock import patch
from django.core.cache import cache
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, override_settings
from django.utils import timezone
from parameterized import parameterized
@@ -36,6 +36,12 @@ def _verification_counter(outcome: str, source: str) -> float:
)
+def _stale_counter() -> float:
+ from prometheus_client import REGISTRY
+
+ return REGISTRY.get_sample_value("conversations_signing_secret_stale_total") or 0.0
+
+
class TestWidgetAPI(BaseTest):
def setUp(self):
super().setUp()
@@ -832,6 +838,45 @@ class TestWidgetIdentityVerification(BaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["count"], 1)
+ @parameterized.expand(
+ [
+ # setUp signs the hash with the value held in team.secret_api_token; with the
+ # kill switch off (#66179) that column must stop verifying — only a current
+ # SigningSecret row may.
+ ("signing_secret_row_verifies", "matching", "current", status.HTTP_200_OK, 0.0),
+ ("legacy_fallback_is_gone", "none", "current", status.HTTP_403_FORBIDDEN, 0.0),
+ # A stale row holds a retired key; accepting it under the switch would
+ # silently un-revoke that key.
+ ("stale_row_stays_excluded", "stale", "retired", status.HTTP_403_FORBIDDEN, 1.0),
+ ]
+ )
+ @override_settings(ACCEPT_TEAM_SECRET_TOKENS=False)
+ def test_list_tickets_with_legacy_tokens_switched_off(
+ self, _name: str, row: str, sign_with: str, expected_status: int, expected_stale_delta: float
+ ) -> None:
+ retired_secret = "a_retired_secret_key"
+ if row != "none":
+ SigningSecret.objects.for_team(self.team.id).create(
+ team=self.team, secret=self.secret if row == "matching" else retired_secret
+ )
+ identity_hash = (
+ self.identity_hash if sign_with == "current" else compute_identity_hash(self.distinct_id, retired_secret)
+ )
+ self._create_ticket()
+ before_stale = _stale_counter()
+
+ response = self.client.get(
+ "/api/conversations/v1/widget/tickets",
+ {
+ "identity_distinct_id": self.distinct_id,
+ "identity_hash": identity_hash,
+ },
+ **self._get_headers(),
+ )
+
+ self.assertEqual(response.status_code, expected_status)
+ self.assertEqual(_stale_counter() - before_stale, expected_stale_delta)
+
def test_list_tickets_post_backfill_reports_the_signing_secret_as_the_source(self):
# After the backfill both stores hold the same value, so the response is 200 either
# way and only the counter shows which one matched. Without this, reordering the
diff --git a/products/conversations/backend/api/widget.py b/products/conversations/backend/api/widget.py
index 53481c0fd9b6..dc483f7e95d6 100644
--- a/products/conversations/backend/api/widget.py
+++ b/products/conversations/backend/api/widget.py
@@ -17,6 +17,7 @@ import logging
from dataclasses import field as dataclass_field
from typing import Literal
+from django.conf import settings
from django.db.models import F, Q
from prometheus_client import Counter
@@ -131,6 +132,10 @@ def _identity_secrets(team: Team) -> list[_IdentitySecret]:
SIGNING_SECRET_STALE_COUNTER.inc()
logger.warning("Conversations signing secret is stale, skipping it", extra={"team_id": team.id})
+ # Kill switch (#66179): legacy tokens stop being verification candidates, but the
+ # staleness guard above already ran, so a row holding a retired key stays excluded.
+ if not settings.ACCEPT_TEAM_SECRET_TOKENS:
+ return secrets
return secrets + legacy_secrets
diff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.py
index 82995d025056..7c12d344b9fd 100644
--- a/products/customer_analytics/backend/presentation/views/external.py
+++ b/products/customer_analytics/backend/presentation/views/external.py
@@ -27,6 +27,7 @@ import hashlib
from typing import Any, cast
from uuid import UUID
+from django.conf import settings
from django.db.models import Q
from django.http import HttpRequest
@@ -150,7 +151,13 @@ class ExternalAccountProjectSecretAPIKeyAuthentication(ProjectSecretAPIKeyAuthen
def authenticate(self, request: HttpRequest | Request) -> tuple[Any, None] | None:
result = super().authenticate(request)
- if result is None or not _customer_analytics_enabled(self.project_secret_api_key.team):
+ if result is None:
+ return None
+ team = self.project_secret_api_key.team
+ # These AllowAny views never run ActiveOrganizationPermission, so organization
+ # state must be enforced here or a key outlives its deactivated organization.
+ organization = team.organization
+ if not organization.is_active or organization.is_pending_deletion or not _customer_analytics_enabled(team):
return None
return result
@@ -183,6 +190,11 @@ class ExternalAccountPersonalKeyAccess(TeamAndOrgViewSetMixin, GenericViewSet):
def _authenticate_team(request: Request) -> tuple[Team, None] | tuple[None, Response]:
"""Extract Bearer token from Authorization header and validate against a team."""
+ # Kill switch (#66179): with legacy tokens off, migrated tokens authenticate as PSAKs
+ # (the deferral also goes inert) and never reach here; the rest get a plain 401.
+ if not settings.ACCEPT_TEAM_SECRET_TOKENS:
+ return None, Response({"error": "Missing or invalid API key"}, status=status.HTTP_401_UNAUTHORIZED)
+
auth_header = request.headers.get("Authorization", "")
if not auth_header.startswith("Bearer "):
return None, Response({"error": "Missing or invalid Authorization header"}, status=status.HTTP_401_UNAUTHORIZED)
@@ -198,9 +210,10 @@ def _authenticate_team(request: Request) -> tuple[Team, None] | tuple[None, Resp
except (Team.DoesNotExist, Team.MultipleObjectsReturned):
return None, Response({"error": "Invalid API key"}, status=status.HTTP_401_UNAUTHORIZED)
- # Same 401 as an unknown token: a valid secret token for a team without customer
- # analytics enabled must not be usable to read account data.
- if not _customer_analytics_enabled(team):
+ # Same 401 as an unknown token: a valid secret token for a blocked organization or a
+ # team without customer analytics enabled must not be usable to read account data.
+ organization = team.organization
+ if not organization.is_active or organization.is_pending_deletion or not _customer_analytics_enabled(team):
return None, Response({"error": "Invalid API key"}, status=status.HTTP_401_UNAUTHORIZED)
TeamSecretTokenAuthentication.record_activity_actor(None)
@@ -638,19 +651,25 @@ class ExternalAccountCustomPropertiesView(APIView):
PATCH /api/customer_analytics/external/account/custom_property_values — Set an account's custom
property values, addressing each property by its definition id (UUID).
- Authenticated via Bearer token (team secret_api_token) in the Authorization header.
+ Accepts the team secret_api_token or a project secret API key with the ``account:write``
+ scope as a Bearer token.
"""
- authentication_classes: list = []
+ authentication_classes = [ExternalAccountProjectSecretAPIKeyAuthentication]
permission_classes = [AllowAny]
- throttle_classes = [ExternalAccountBurstThrottle, ExternalAccountSustainedThrottle]
+ throttle_classes = [
+ ExternalAccountBurstThrottle,
+ ExternalAccountSustainedThrottle,
+ ExternalAccountTeamBurstThrottle,
+ ExternalAccountTeamSustainedThrottle,
+ ]
@extend_schema(request=ExternalAccountCustomPropertiesSerializer, responses={200: OpenApiTypes.OBJECT})
def patch(self, request: Request) -> Response:
- team, error = _authenticate_team(request)
+ team, error = _authenticate_team_for_update(request)
if error:
return error
assert team is not None
- ACCOUNT_ACTION_AUTH_COUNTER.labels(auth_method="secret_api_token", http_method="patch").inc()
+ ACCOUNT_ACTION_AUTH_COUNTER.labels(auth_method=_get_auth_method_label(request), http_method="patch").inc()
return handle_account_set_properties(request, team)
diff --git a/products/customer_analytics/backend/test/test_external.py b/products/customer_analytics/backend/test/test_external.py
index d3ccb578d085..1e8b87edee86 100644
--- a/products/customer_analytics/backend/test/test_external.py
+++ b/products/customer_analytics/backend/test/test_external.py
@@ -181,6 +181,25 @@ class TestExternalAccountAPI(APIBaseTest):
self.account.refresh_from_db()
self.assertIsNotNone(self.account.churned_at)
+ @override_settings(ACCEPT_TEAM_SECRET_TOKENS=False)
+ def test_kill_switch_off_migrated_token_lacks_account_scopes(self) -> None:
+ # Flip semantics (#66179): the mirror rows carry only flag/ticket read scopes, so on
+ # this surface a migrated legacy token resolves as a PSAK and fails the scope check.
+ # Legacy traffic here was confirmed at zero before shipping the switch.
+ create_project_secret_api_key(
+ self.team,
+ label="Migrated legacy secret API key",
+ scopes=["feature_flag:read", "support_ticket:read"],
+ value=self.team.secret_api_token,
+ )
+ response = self._get()
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ @override_settings(ACCEPT_TEAM_SECRET_TOKENS=False)
+ def test_kill_switch_off_rejects_legacy_token_without_mirror_row(self) -> None:
+ response = self._get()
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+
def test_post_accepts_project_secret_api_key_with_account_write_scope(self) -> None:
token = self._create_psak_token(scopes=["account:write"])
@@ -193,6 +212,28 @@ class TestExternalAccountAPI(APIBaseTest):
accounts = Account.objects.for_team(self.team.id).filter(external_id="acme-2")
self.assertEqual([account.name for account in accounts], ["Acme Two"])
+ @parameterized.expand(
+ [
+ (f"{credential}_{name}", credential, changes)
+ for credential in ("psak", "legacy_token")
+ for name, changes in [
+ ("organization_deactivated", {"is_active": False}),
+ ("organization_active_null", {"is_active": None}),
+ ("organization_pending_deletion", {"is_pending_deletion": True}),
+ ]
+ ]
+ )
+ def test_credentials_are_rejected_when_the_organization_is_blocked(
+ self, _name: str, credential: str, changes: dict
+ ) -> None:
+ token = self._create_psak_token(scopes=["account:read"]) if credential == "psak" else None
+ for field, value in changes.items():
+ setattr(self.organization, field, value)
+ self.organization.save()
+
+ response = self._get(token=token)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+
def test_project_secret_api_keys_share_a_team_rate_limit(self):
cache.clear()
self.addCleanup(cache.clear)
@@ -748,6 +789,42 @@ class TestExternalAccountCustomPropertiesAPI(APIBaseTest):
response = self.client.patch(self.url, data={"external_id": "acme-1", "properties": {}}, format="json")
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ @parameterized.expand(
+ [
+ ("write_scope", ["account:write"], status.HTTP_200_OK),
+ ("read_scope", ["account:read"], status.HTTP_403_FORBIDDEN),
+ ]
+ )
+ def test_project_secret_api_key_needs_account_write(self, _name: str, scopes: list[str], expected: int) -> None:
+ _, token = create_project_secret_api_key(self.team, label="props", scopes=scopes)
+ response = self._patch({"external_id": "acme-1", "properties": {str(self.plan.id): "enterprise"}}, token=token)
+ self.assertEqual(response.status_code, expected)
+
+ @override_settings(ACCEPT_TEAM_SECRET_TOKENS=False)
+ def test_kill_switch_off_account_write_key_still_sets_values(self) -> None:
+ _, token = create_project_secret_api_key(self.team, label="props", scopes=["account:write"])
+ response = self._patch({"external_id": "acme-1", "properties": {str(self.plan.id): "enterprise"}}, token=token)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ def test_project_secret_api_keys_share_a_team_rate_limit(self) -> None:
+ cache.clear()
+ self.addCleanup(cache.clear)
+ first_token = create_project_secret_api_key(self.team, label="first", scopes=["account:write"])[1]
+ second_token = create_project_secret_api_key(self.team, label="second", scopes=["account:write"])[1]
+
+ with (
+ patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True),
+ patch(
+ "products.customer_analytics.backend.presentation.views.external.ExternalAccountTeamBurstThrottle.rate",
+ "1/minute",
+ ),
+ ):
+ first = self._patch({"external_id": "acme-1", "properties": {}}, token=first_token)
+ second = self._patch({"external_id": "acme-1", "properties": {}}, token=second_token)
+
+ self.assertEqual(first.status_code, status.HTTP_200_OK)
+ self.assertEqual(second.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+
def test_sets_values_by_definition_id(self):
response = self._patch(
{"external_id": "acme-1", "properties": {str(self.plan.id): "enterprise", str(self.seats.id): 42}}