: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(auth): remove secret token body support (#71753)
Patricio39f775bd183c
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.pyindex d6006bcafcee..979c6f2c899b 100644--- a/posthog/api/test/test_authentication.py+++ b/posthog/api/test/test_authentication.py@@ -1977,8 +1977,8 @@ class TestTeamSecretTokenAuthentication(APIBaseTest):access_method=AccessMethod.TEAM_SECRET_TOKEN,)- def test_authenticate_with_valid_secret_api_key_in_body(self):- # Simulate a request with a valid team secret token+ 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("/",data=f'{{"secret_api_key": "{self.team.secret_api_token}"}}',@@ -1989,12 +1989,8 @@ class TestTeamSecretTokenAuthentication(APIBaseTest):authenticator = TeamSecretTokenAuthentication()result = authenticator.authenticate(request)- assert result is not None- user, _ = result- self.assertIsNotNone(user)- self.assertIsInstance(user, TeamSecretTokenUser)- self.assertEqual(user.team, self.team)+ self.assertIsNone(result)def test_authenticate_with_secret_api_key_in_query_string_not_supported(self):# Query string authentication should not be supported for security reasons@@ -2064,25 +2060,6 @@ class TestTeamSecretTokenAuthentication(APIBaseTest):self.assertIsInstance(user, TeamSecretTokenUser)self.assertEqual(user.team, self.team)- @parameterized.expand(- [- ("public_token", "phc_test_public_token"),- ("non_prefixed_token", "some_random_token_without_prefix"),- ("empty_string", ""),- ("integer_value", 12345),- ]- )- def test_authenticate_with_invalid_token_in_body_rejected(self, _name, token_value):- data = json.dumps({"secret_api_key": token_value})- wsgi_request = self.factory.post("/", data=data, content_type="application/json")- request = Request(wsgi_request)- request.parsers = [JSONParser()]-- authenticator = TeamSecretTokenAuthentication()- result = authenticator.authenticate(request)-- self.assertIsNone(result)-class TestSyntheticUser(SimpleTestCase):def _team(self, team_id=42):@@ -2136,38 +2113,12 @@ class TestExtractPhsToken(SimpleTestCase):def setUp(self):self.factory = APIRequestFactory()- @parameterized.expand(- [- ("list_body", "[1, 2, 3]"),- ("string_body", '"hello"'),- ("number_body", "42"),- ("null_body", "null"),- ]- )- def test_non_dict_body_returns_none(self, _name, raw_body):- wsgi_request = self.factory.post("/", data=raw_body, content_type="application/json")- request = Request(wsgi_request)- request.parsers = [JSONParser()]-- self.assertIsNone(_extract_phs_token(request, allow_body_token=True))-def test_valid_token_in_header_returned(self):token = "phs_" + "x" * 35wsgi_request = self.factory.get("/", HTTP_AUTHORIZATION=f"Bearer {token}")self.assertEqual(_extract_phs_token(Request(wsgi_request)), token)- def test_valid_token_in_dict_body_returned_when_body_allowed(self):- token = "phs_" + "y" * 35- wsgi_request = self.factory.post(- "/",- data=json.dumps({"secret_api_key": token}),- content_type="application/json",- )- request = Request(wsgi_request)- request.parsers = [JSONParser()]- self.assertEqual(_extract_phs_token(request, allow_body_token=True), token)-- def test_body_token_ignored_when_body_not_allowed(self):+ def test_body_token_ignored(self):token = "phs_" + "y" * 35wsgi_request = self.factory.post("/",@@ -2176,7 +2127,7 @@ class TestExtractPhsToken(SimpleTestCase):)request = Request(wsgi_request)request.parsers = [JSONParser()]- self.assertIsNone(_extract_phs_token(request, allow_body_token=False))+ self.assertIsNone(_extract_phs_token(request))def test_no_token_anywhere_returns_none(self):wsgi_request = self.factory.get("/")@@ -2224,7 +2175,7 @@ class TestProjectSecretAPIKeyAuthentication(APIBaseTest):)def test_authenticate_with_psak_in_body_returns_none(self):- # PSAK auth is header-only (allow_body_token=False): a token in the request body must not authenticate.+ # PSAK auth is header-only: a token in the request body must not authenticate.wsgi_request = self.factory.post("/",data=json.dumps({"secret_api_key": self.token}),diff --git a/posthog/auth.py b/posthog/auth.pyindex 630ecccc1e98..63fd1c58b5b8 100644--- a/posthog/auth.py+++ b/posthog/auth.py@@ -70,13 +70,6 @@ tracer = trace.get_tracer(__name__)_SECRET_API_KEY_RE = re.compile(r"^phs_[a-zA-Z0-9]+$")-SECRET_API_KEY_BODY_FIELD = "secret_api_key"--SECRET_API_KEY_BODY_COUNTER = Counter(- "api_auth_secret_api_key_body",- "Requests where the team secret token is provided in the request body instead of the Authorization header",-)-PERSONAL_API_KEY_QUERY_PARAM_COUNTER = Counter("api_auth_personal_api_key_query_param","Requests where the personal api key is specified in a query parameter",@@ -333,11 +326,10 @@ class PersonalAPIKeyAuthentication(authentication.BaseAuthentication):return cls.keyword-def _extract_phs_token(request: Union[HttpRequest, Request], allow_body_token: bool = False) -> Optional[str]:+def _extract_phs_token(request: Union[HttpRequest, Request]) -> Optional[str]:"""- Find a `phs_` secret token in the request. Checks the Authorization header first- (Bearer scheme), then the request body field `secret_api_key`. Used by both- TeamSecretTokenAuthentication (legacy Team.secret_api_token) and+ Find a `phs_` secret token in the request Authorization header (Bearer scheme).+ Used by both TeamSecretTokenAuthentication (legacy Team.secret_api_token) andProjectSecretAPIKeyAuthentication (PSAK model)."""if "authorization" in request.headers:@@ -347,17 +339,6 @@ def _extract_phs_token(request: Union[HttpRequest, Request], allow_body_token: bif _SECRET_API_KEY_RE.match(token):return token- if allow_body_token:- # Wrap HttpRequest in a DRF Request only when we actually need to read the parsed body.- if not isinstance(request, Request):- request = Request(request)- data = request.data- if isinstance(data, dict):- candidate = data.get(SECRET_API_KEY_BODY_FIELD)- if isinstance(candidate, str) and _SECRET_API_KEY_RE.match(candidate):- SECRET_API_KEY_BODY_COUNTER.inc()- return candidate-return None@@ -383,15 +364,13 @@ class TeamSecretTokenAuthentication(authentication.BaseAuthentication):attached, so downstream permission code can resolve team context without areal User.- Only the first key candidate found in the request is tried, and the order is:- 1. Request Authorization header of type Bearer.- 2. Request body (`secret_api_key` field).+ The token is read from the Authorization header (Bearer scheme) only."""keyword = "Bearer"def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:- secret_api_token = _extract_phs_token(request, allow_body_token=True)+ secret_api_token = _extract_phs_token(request)if not secret_api_token:return None@@ -449,7 +428,7 @@ class ProjectSecretAPIKeyAuthentication(authentication.BaseAuthentication):keyword = "Bearer"def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:- token = _extract_phs_token(request, allow_body_token=False)+ token = _extract_phs_token(request)if not token:return None