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 ProjectSecretAPIKey auth machinery (unwired) (#62550)

Jovan Sakovic29ba81c7e4b9
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 4aba29f5e50a..6952156caf43 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -2467,6 +2467,7 @@ export interface ProjectSecretAPIKeyApi {
readonly last_used_at: string | null
/** @nullable */
readonly last_rolled_at: string | null
+ /** Project-wide API scopes granted to this key. Project secret API keys do not honor object-level access controls, so a scope can access resources of that type even when per-resource RBAC would hide them from an individual user. */
scopes: string[]
}
@@ -2492,6 +2493,7 @@ export interface PatchedProjectSecretAPIKeyApi {
readonly last_used_at?: string | null
/** @nullable */
readonly last_rolled_at?: string | null
+ /** Project-wide API scopes granted to this key. Project secret API keys do not honor object-level access controls, so a scope can access resources of that type even when per-resource RBAC would hide them from an individual user. */
scopes?: string[]
}
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index 7ed4b74962bd..e24166f018ef 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -3221,21 +3221,34 @@ export const projectSecretApiKeysCreateBodyLabelMax = 40
export const ProjectSecretApiKeysCreateBody = /* @__PURE__ */ zod.object({
label: zod.string().max(projectSecretApiKeysCreateBodyLabelMax),
- scopes: zod.array(zod.string()),
+ scopes: zod
+ .array(zod.string())
+ .describe(
+ 'Project-wide API scopes granted to this key. Project secret API keys do not honor object-level access controls, so a scope can access resources of that type even when per-resource RBAC would hide them from an individual user.'
+ ),
})
export const projectSecretApiKeysUpdateBodyLabelMax = 40
export const ProjectSecretApiKeysUpdateBody = /* @__PURE__ */ zod.object({
label: zod.string().max(projectSecretApiKeysUpdateBodyLabelMax),
- scopes: zod.array(zod.string()),
+ scopes: zod
+ .array(zod.string())
+ .describe(
+ 'Project-wide API scopes granted to this key. Project secret API keys do not honor object-level access controls, so a scope can access resources of that type even when per-resource RBAC would hide them from an individual user.'
+ ),
})
export const projectSecretApiKeysPartialUpdateBodyLabelMax = 40
export const ProjectSecretApiKeysPartialUpdateBody = /* @__PURE__ */ zod.object({
label: zod.string().max(projectSecretApiKeysPartialUpdateBodyLabelMax).optional(),
- scopes: zod.array(zod.string()).optional(),
+ scopes: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Project-wide API scopes granted to this key. Project secret API keys do not honor object-level access controls, so a scope can access resources of that type even when per-resource RBAC would hide them from an individual user.'
+ ),
})
export const PropertyDefinitionsUpdateBody = /* @__PURE__ */ zod
diff --git a/posthog/api/project_secret_api_key.py b/posthog/api/project_secret_api_key.py
index 1efadf991824..b16f636a01d7 100644
--- a/posthog/api/project_secret_api_key.py
+++ b/posthog/api/project_secret_api_key.py
@@ -29,12 +29,20 @@ from posthog.scopes import (
PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION,
)
-MAX_PROJECT_SECRET_API_KEYS_PER_TEAM = 10
+MAX_PROJECT_SECRET_API_KEYS_PER_TEAM = 50
class ProjectSecretAPIKeySerializer(serializers.ModelSerializer):
value = serializers.SerializerMethodField(method_name="get_key_value", read_only=True)
- scopes = serializers.ListField(child=serializers.CharField(required=True), allow_empty=False)
+ scopes = serializers.ListField(
+ child=serializers.CharField(required=True),
+ allow_empty=False,
+ help_text=(
+ "Project-wide API scopes granted to this key. Project secret API keys do not honor object-level "
+ "access controls, so a scope can access resources of that type even when per-resource RBAC would "
+ "hide them from an individual user."
+ ),
+ )
created_by = UserBasicSerializer(read_only=True)
class Meta:
@@ -139,6 +147,7 @@ class ProjectSecretAPIKeySerializer(serializers.ModelSerializer):
@extend_schema(extensions={"x-product": "core"})
class ProjectSecretAPIKeyViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
scope_object = "project"
+ scope_object_write_actions = ["create", "update", "partial_update", "patch", "destroy", "roll"]
lookup_field = "id"
serializer_class = ProjectSecretAPIKeySerializer
permission_classes = [TimeSensitiveActionPermission, TeamMemberStrictManagementPermission]
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.py
index f55e8ed4b456..44d29a463120 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -16,7 +16,7 @@ from django.core import mail
from django.core.asgi import get_asgi_application
from django.core.cache import cache
from django.http import HttpResponse
-from django.test import RequestFactory, override_settings
+from django.test import RequestFactory, SimpleTestCase, override_settings
from django.utils import timezone
from asgiref.sync import sync_to_async
@@ -38,9 +38,13 @@ from posthog.api.oauth.test_dcr import generate_rsa_key
from posthog.auth import (
InternalAPIUser,
OAuthAccessTokenAuthentication,
+ ProjectSecretAPIKeyAuthentication,
+ ProjectSecretAPIKeyUser,
TeamSecretTokenAuthentication,
TeamSecretTokenUser,
+ _extract_phs_token,
)
+from posthog.clickhouse.query_tagging import AccessMethod
from posthog.helpers.user_devices import (
KNOWN_DEVICE_COOKIE,
build_known_device_cookie_value,
@@ -53,6 +57,7 @@ from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.project_secret_api_key import ProjectSecretAPIKey
from posthog.models.team.team import Team
from posthog.models.utils import generate_random_token_personal, hash_key_value
@@ -1938,6 +1943,18 @@ class TestTeamSecretTokenAuthentication(APIBaseTest):
self.assertIsInstance(user, TeamSecretTokenUser)
self.assertEqual(user.team, self.team)
+ def test_authenticate_tags_queries_with_team_secret_token_access_method(self):
+ wsgi_request = self.factory.get("/", headers={"AUTHORIZATION": f"Bearer {self.team.secret_api_token}"})
+ request = Request(wsgi_request)
+ authenticator = TeamSecretTokenAuthentication()
+ with patch("posthog.auth.tag_authentication") as mock_tag_authentication:
+ authenticator.authenticate(request)
+ mock_tag_authentication.assert_called_once_with(
+ user_id=None,
+ team_id=self.team.id,
+ 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
wsgi_request = self.factory.post(
@@ -2045,6 +2062,227 @@ class TestTeamSecretTokenAuthentication(APIBaseTest):
self.assertIsNone(result)
+class TestSyntheticUser(SimpleTestCase):
+ def _team(self, team_id=42):
+ return type("FakeTeam", (), {"id": team_id})()
+
+ def test_base_class_requires_distinct_id(self):
+ from posthog.synthetic_user import SyntheticUser
+
+ with self.assertRaises(TypeError):
+ SyntheticUser(self._team()) # type: ignore[call-arg]
+
+ def test_team_secret_token_user_distinct_id_includes_team_id(self):
+ user = TeamSecretTokenUser(self._team(team_id=42))
+ self.assertEqual(user.distinct_id, "team-secret-token-42")
+ self.assertEqual(user.current_team_id, 42)
+ self.assertTrue(user.is_authenticated)
+ self.assertIsNone(user.id)
+
+ def test_project_secret_api_key_user_carries_psak_and_distinct_id(self):
+ team = self._team(team_id=7)
+ fake_psak = type(
+ "FakePSAK",
+ (),
+ {"team": team, "team_id": team.id, "id": 99, "scopes": ["endpoint:read"]},
+ )()
+ user = ProjectSecretAPIKeyUser(fake_psak)
+ self.assertEqual(user.distinct_id, "psak-7-99")
+ self.assertIs(user.project_secret_api_key, fake_psak)
+ self.assertIsNone(user.id)
+
+ def test_isinstance_check_recognises_both_subclasses(self):
+ from posthog.synthetic_user import SyntheticUser
+
+ team = self._team()
+ fake_psak = type("FakePSAK", (), {"team": team, "team_id": team.id, "id": 1, "scopes": []})()
+ self.assertIsInstance(TeamSecretTokenUser(team), SyntheticUser)
+ self.assertIsInstance(ProjectSecretAPIKeyUser(fake_psak), SyntheticUser)
+
+ def test_mutable_attrs_are_isolated_per_instance(self):
+ a = TeamSecretTokenUser(self._team(team_id=1))
+ b = TeamSecretTokenUser(self._team(team_id=2))
+
+ a.groups.append("x")
+ a.user_permissions.append("y")
+
+ self.assertEqual(b.groups, [])
+ self.assertEqual(b.user_permissions, [])
+
+
+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" * 35
+ wsgi_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):
+ 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.assertIsNone(_extract_phs_token(request, allow_body_token=False))
+
+ def test_no_token_anywhere_returns_none(self):
+ wsgi_request = self.factory.get("/")
+ self.assertIsNone(_extract_phs_token(Request(wsgi_request)))
+
+
+class TestProjectSecretAPIKeyAuthentication(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.factory = APIRequestFactory()
+ self.token = "phs_" + "a" * 35
+ self.psak = ProjectSecretAPIKey.objects.create(
+ team=self.team,
+ label="psak-test",
+ mask_value="phs_...aaaa",
+ secure_value=hash_key_value(self.token),
+ scopes=["endpoint:read"],
+ )
+
+ def _request_with_header(self, token):
+ wsgi_request = self.factory.get("/", HTTP_AUTHORIZATION=f"Bearer {token}")
+ return Request(wsgi_request)
+
+ def test_authenticate_with_valid_psak_in_header(self):
+ authenticator = ProjectSecretAPIKeyAuthentication()
+ result = authenticator.authenticate(self._request_with_header(self.token))
+
+ assert result is not None
+ user, _ = result
+ self.assertIsInstance(user, ProjectSecretAPIKeyUser)
+ self.assertEqual(user.team, self.team)
+ self.assertEqual(user.project_secret_api_key.pk, self.psak.pk)
+ self.assertEqual(authenticator.project_secret_api_key.pk, self.psak.pk)
+
+ def test_authenticate_tags_queries_with_psak_access_method(self):
+ authenticator = ProjectSecretAPIKeyAuthentication()
+ with patch("posthog.auth.tag_authentication") as mock_tag_authentication:
+ authenticator.authenticate(self._request_with_header(self.token))
+ mock_tag_authentication.assert_called_once_with(
+ user_id=None,
+ team_id=self.team.id,
+ access_method=AccessMethod.PROJECT_SECRET_API_KEY,
+ api_key_mask=self.psak.mask_value,
+ api_key_label=self.psak.label,
+ )
+
+ 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.
+ wsgi_request = self.factory.post(
+ "/",
+ data=json.dumps({"secret_api_key": self.token}),
+ content_type="application/json",
+ )
+ request = Request(wsgi_request)
+ request.parsers = [JSONParser()]
+
+ authenticator = ProjectSecretAPIKeyAuthentication()
+ result = authenticator.authenticate(request)
+
+ self.assertIsNone(result)
+
+ def test_authenticate_with_unknown_token_returns_none(self):
+ unknown_token = "phs_" + "z" * 35
+ authenticator = ProjectSecretAPIKeyAuthentication()
+ result = authenticator.authenticate(self._request_with_header(unknown_token))
+ self.assertIsNone(result)
+
+ def test_does_not_fall_back_to_team_secret_api_token(self):
+ # Set Team.secret_api_token to a legacy token; PSAK auth should ignore it.
+ legacy_token = "phs_" + "b" * 35
+ self.team.secret_api_token = legacy_token
+ self.team.save()
+
+ authenticator = ProjectSecretAPIKeyAuthentication()
+ result = authenticator.authenticate(self._request_with_header(legacy_token))
+ self.assertIsNone(result)
+
+ def test_authenticate_without_token_returns_none(self):
+ wsgi_request = self.factory.get("/")
+ authenticator = ProjectSecretAPIKeyAuthentication()
+ result = authenticator.authenticate(Request(wsgi_request))
+ self.assertIsNone(result)
+
+ @parameterized.expand(
+ [
+ ("public_token", "phc_test_public_token"),
+ ("unprefixed", "some_random_token"),
+ ("empty", ""),
+ ]
+ )
+ def test_authenticate_with_wrong_prefix_returns_none(self, _name, token):
+ authenticator = ProjectSecretAPIKeyAuthentication()
+ result = authenticator.authenticate(self._request_with_header(token))
+ self.assertIsNone(result)
+
+ def test_last_used_at_updates_on_first_use(self):
+ assert self.psak.last_used_at is None
+ authenticator = ProjectSecretAPIKeyAuthentication()
+ authenticator.authenticate(self._request_with_header(self.token))
+
+ self.psak.refresh_from_db()
+ self.assertIsNotNone(self.psak.last_used_at)
+
+ def test_last_used_at_hourly_throttle_skips_recent(self):
+ recent = timezone.now() - timedelta(minutes=30)
+ ProjectSecretAPIKey.objects.filter(pk=self.psak.pk).update(last_used_at=recent)
+
+ authenticator = ProjectSecretAPIKeyAuthentication()
+ authenticator.authenticate(self._request_with_header(self.token))
+
+ self.psak.refresh_from_db()
+ # Should not update if less than 1 hour has passed
+ assert self.psak.last_used_at is not None
+ assert abs((self.psak.last_used_at - recent).total_seconds()) < 1
+
+ def test_last_used_at_updates_after_one_hour(self):
+ old = timezone.now() - timedelta(hours=2)
+ ProjectSecretAPIKey.objects.filter(pk=self.psak.pk).update(last_used_at=old)
+
+ authenticator = ProjectSecretAPIKeyAuthentication()
+ authenticator.authenticate(self._request_with_header(self.token))
+
+ self.psak.refresh_from_db()
+ assert self.psak.last_used_at is not None
+ # Should have updated to a recent timestamp
+ self.assertGreater(self.psak.last_used_at, old + timedelta(hours=1))
+
+
@override_settings(
OAUTH2_PROVIDER={
**settings.OAUTH2_PROVIDER,
@@ -2153,8 +2391,8 @@ class TestOAuthAccessTokenAuthentication(APIBaseTest):
self.assertIsNone(result)
- @patch("posthog.auth.tag_queries")
- def test_authenticate_tags_queries_correctly(self, mock_tag_queries):
+ @patch("posthog.auth.tag_authentication")
+ def test_authenticate_tags_queries_correctly(self, mock_tag_authentication):
wsgi_request = self.factory.get(
"/",
headers={"AUTHORIZATION": f"Bearer {self.access_token.token}"},
@@ -2166,7 +2404,7 @@ class TestOAuthAccessTokenAuthentication(APIBaseTest):
self.assertIsNotNone(result)
- mock_tag_queries.assert_called_once_with(
+ mock_tag_authentication.assert_called_once_with(
user_id=self.user.pk,
team_id=self.team.pk,
access_method="oauth",
@@ -2260,7 +2498,7 @@ class TestOAuthAccessTokenAuthentication(APIBaseTest):
def test_oauth_access_token_calls_tag_queries_with_correct_parameters(self):
"""Test that tag_queries is called with the correct user_id and team_id."""
- with patch("posthog.auth.tag_queries") as mock_tag_queries:
+ with patch("posthog.auth.tag_authentication") as mock_tag_authentication:
wsgi_request = self.factory.get(
"/",
headers={"AUTHORIZATION": f"Bearer {self.access_token.token}"},
@@ -2275,7 +2513,7 @@ class TestOAuthAccessTokenAuthentication(APIBaseTest):
self.assertIsInstance(self.user.current_team_id, int)
# Verify tag_queries was called with correct parameters
- mock_tag_queries.assert_called_once_with(
+ mock_tag_authentication.assert_called_once_with(
user_id=self.user.pk,
team_id=self.user.current_team_id,
access_method="oauth",
@@ -2492,7 +2730,7 @@ async def test_known_device_cookie_async_chain_with_project_secret_api_key():
set_known_device_cookie(response, request.user)
File "posthog/helpers/user_devices.py", in set_known_device_cookie
KNOWN_DEVICE_COOKIE.format(user_id=user.id),
- AttributeError: 'TeamSecretTokenUser' object has no attribute 'id'
+ AttributeError: 'ProjectSecretAPIKeyUser' object has no attribute 'id'
Drives the real ASGI middleware chain via httpx + ASGITransport (patterned after
posthog-python's integration_tests/django5). Sync `Client` skips the ASGI app and so
diff --git a/posthog/api/test/test_project_secret_api_keys.py b/posthog/api/test/test_project_secret_api_keys.py
index 7b2dbf0384c8..1b21479fcd53 100644
--- a/posthog/api/test/test_project_secret_api_keys.py
+++ b/posthog/api/test/test_project_secret_api_keys.py
@@ -2,7 +2,9 @@ from posthog.test.base import APIBaseTest
from posthog.api.project_secret_api_key import MAX_PROJECT_SECRET_API_KEYS_PER_TEAM
from posthog.models import Organization, OrganizationMembership, Team
+from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.project_secret_api_key import ProjectSecretAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
class TestProjectSecretAPIKeysAPIMember(APIBaseTest):
@@ -331,3 +333,123 @@ class TestProjectSecretAPIKeysAPI(APIBaseTest):
assert logs[0].detail is not None
assert logs[0].detail["name"] == "delete me"
assert logs[0].team_id == self.team.id
+
+
+class TestProjectSecretAPIKeysViaPersonalAPIKey(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ self.client.logout()
+
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="pat-with-project-write",
+ user=self.user,
+ scopes=["project:write", "project:read"],
+ secure_value=hash_key_value(token),
+ )
+ self.token = token
+
+ def _auth(self):
+ return {"HTTP_AUTHORIZATION": f"Bearer {self.token}"}
+
+ def _create_key(self) -> str:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/project_secret_api_keys/",
+ data={"label": "rollable", "scopes": ["endpoint:read"]},
+ content_type="application/json",
+ **self._auth(),
+ )
+ assert response.status_code == 201, response.content
+ return response.json()["id"]
+
+ def test_roll_works_via_pat_with_project_write(self):
+ key_id = self._create_key()
+ original = ProjectSecretAPIKey.objects.get(id=key_id)
+ original_secure_value = original.secure_value
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/project_secret_api_keys/{key_id}/roll/",
+ **self._auth(),
+ )
+
+ assert response.status_code == 200, response.content
+ rolled = response.json()
+ assert rolled["value"] is not None
+ assert rolled["value"].startswith("phs_")
+
+ original.refresh_from_db()
+ assert original.secure_value != original_secure_value
+ assert original.secure_value == hash_key_value(rolled["value"])
+
+ def test_roll_rejected_for_pat_without_project_write(self):
+ key_id = self._create_key()
+
+ readonly_token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="pat-readonly",
+ user=self.user,
+ scopes=["project:read"],
+ secure_value=hash_key_value(readonly_token),
+ )
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/project_secret_api_keys/{key_id}/roll/",
+ HTTP_AUTHORIZATION=f"Bearer {readonly_token}",
+ )
+ assert response.status_code == 403, response.content
+
+ def test_destroy_works_via_pat(self):
+ key_id = self._create_key()
+
+ response = self.client.delete(
+ f"/api/projects/{self.team.id}/project_secret_api_keys/{key_id}/",
+ **self._auth(),
+ )
+ assert response.status_code == 204, response.content
+ assert not ProjectSecretAPIKey.objects.filter(id=key_id).exists()
+
+ def test_update_label_via_pat_with_project_write(self):
+ key_id = self._create_key()
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/project_secret_api_keys/{key_id}/",
+ data={"label": "renamed"},
+ content_type="application/json",
+ **self._auth(),
+ )
+ assert response.status_code == 200, response.content
+ assert ProjectSecretAPIKey.objects.get(id=key_id).label == "renamed"
+
+ def test_update_via_pat_rejected_without_project_write(self):
+ key_id = self._create_key()
+
+ readonly_token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="pat-readonly-update",
+ user=self.user,
+ scopes=["project:read"],
+ secure_value=hash_key_value(readonly_token),
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/project_secret_api_keys/{key_id}/",
+ data={"label": "should-fail"},
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {readonly_token}",
+ )
+ assert response.status_code == 403, response.content
+ assert ProjectSecretAPIKey.objects.get(id=key_id).label == "rollable"
+
+ def test_full_update_via_pat_with_project_write(self):
+ key_id = self._create_key()
+
+ response = self.client.put(
+ f"/api/projects/{self.team.id}/project_secret_api_keys/{key_id}/",
+ data={"label": "via-put", "scopes": ["endpoint:read"]},
+ content_type="application/json",
+ **self._auth(),
+ )
+ assert response.status_code == 200, response.content
+ assert ProjectSecretAPIKey.objects.get(id=key_id).label == "via-put"
diff --git a/posthog/api/test/test_routing.py b/posthog/api/test/test_routing.py
index 849de480555f..7b99ac31ed5f 100644
--- a/posthog/api/test/test_routing.py
+++ b/posthog/api/test/test_routing.py
@@ -19,11 +19,13 @@ from rest_framework.response import Response
from posthog.api.oauth.test_dcr import generate_rsa_key
from posthog.api.routing import DefaultRouterPlusPlus, RouterRegistry, TeamAndOrgViewSetMixin
+from posthog.auth import ProjectSecretAPIKeyAuthentication
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.organization import Organization
from posthog.models.project import Project
from posthog.models.scoping import get_current_team_id
from posthog.models.team.team import Team
+from posthog.permissions import APIScopePermission
from products.annotations.backend.api.annotation import AnnotationSerializer
from products.annotations.backend.models.annotation import Annotation
@@ -380,6 +382,16 @@ def _url_signature(router):
return sorted((str(pattern.pattern), pattern.name) for pattern in router.urls)
+def _iter_router_viewset_actions(router):
+ for pattern in router.urls:
+ callback = getattr(pattern, "callback", None)
+ viewset_class = getattr(callback, "cls", None)
+ actions = getattr(callback, "actions", None)
+ if viewset_class is None or actions is None:
+ continue
+ yield pattern.name, viewset_class, set(actions.values())
+
+
def test_product_route_discovery_is_order_independent():
modules = _discover_product_route_modules()
assert modules, "expected to discover product route modules"
@@ -407,6 +419,62 @@ def test_every_discovered_routes_module_is_callable():
assert not missing, f"routes modules without a register_routes callable: {missing}"
+def test_project_secret_api_key_authentication_routes_include_api_scope_permission():
+ from posthog.api import router
+
+ _assert_project_secret_api_key_routes_include_api_scope_permission(router)
+
+
+def _assert_project_secret_api_key_routes_include_api_scope_permission(router):
+ missing = []
+ authenticator = ProjectSecretAPIKeyAuthentication()
+ for route_name, viewset_class, actions in _iter_router_viewset_actions(router):
+ if ProjectSecretAPIKeyAuthentication not in viewset_class.authentication_classes:
+ continue
+
+ for action_name in actions:
+ view = viewset_class()
+ view.action = action_name
+ view.request = type("Request", (), {"successful_authenticator": authenticator})()
+ view.kwargs = {}
+ permissions = view.get_permissions()
+ if not any(isinstance(permission, APIScopePermission) for permission in permissions):
+ missing.append(f"{route_name}:{viewset_class.__name__}.{action_name}")
+
+ assert not missing, (
+ "ProjectSecretAPIKeyAuthentication routes must include APIScopePermission from get_permissions(): "
+ + ", ".join(sorted(missing))
+ )
+
+
+def test_project_secret_api_key_route_contract_fails_without_api_scope_permission():
+ class MisconfiguredPSAKViewSet(viewsets.GenericViewSet):
+ authentication_classes = [ProjectSecretAPIKeyAuthentication]
+
+ def list(self, request):
+ return Response({})
+
+ router = DefaultRouterPlusPlus()
+ router.register(r"misconfigured-psak", MisconfiguredPSAKViewSet, "misconfigured_psak")
+
+ with pytest.raises(AssertionError, match="misconfigured_psak-list:MisconfiguredPSAKViewSet.list"):
+ _assert_project_secret_api_key_routes_include_api_scope_permission(router)
+
+
+def test_project_secret_api_key_route_contract_passes_with_team_and_org_mixin():
+ class ConfiguredPSAKViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ authentication_classes = [ProjectSecretAPIKeyAuthentication]
+ scope_object = "endpoint"
+
+ def list(self, request):
+ return Response({})
+
+ router = DefaultRouterPlusPlus()
+ router.register(r"configured-psak", ConfiguredPSAKViewSet, "configured_psak")
+
+ _assert_project_secret_api_key_routes_include_api_scope_permission(router)
+
+
def test_router_registry_add_rejects_products_caller():
registry = RouterRegistry()
item = DefaultRouterPlusPlus().register(r"things", FooViewSet, "things")
diff --git a/posthog/auth.py b/posthog/auth.py
index 9ba5427fea25..57a92c3680a5 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -28,7 +28,7 @@ from rest_framework.request import Request
from webauthn.helpers import base64url_to_bytes
from zxcvbn import zxcvbn
-from posthog.clickhouse.query_tagging import tag_queries
+from posthog.clickhouse.query_tagging import AccessMethod, tag_authentication
from posthog.constants import AvailableFeature
from posthog.helpers.two_factor_session import enforce_two_factor
from posthog.jwt import PosthogJwtAudience, decode_jwt, get_oidc_verification_keys
@@ -39,12 +39,14 @@ from posthog.models.personal_api_key import (
PERSONAL_API_KEY_MODES_TO_TRY,
PersonalAPIKey,
)
+from posthog.models.project_secret_api_key import ProjectSecretAPIKey, find_project_secret_api_key
from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.user import User
from posthog.models.utils import hash_key_value
from posthog.models.webauthn_credential import WebauthnCredential
from posthog.passkey import verify_passkey_authentication_response
from posthog.settings import LOCAL_DEV_INTERNAL_API_SECRET
+from posthog.synthetic_user import SyntheticUser
class WebAuthnAuthenticationResponse(TypedDict):
@@ -66,6 +68,8 @@ 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",
@@ -309,10 +313,10 @@ class PersonalAPIKeyAuthentication(authentication.BaseAuthentication):
assert personal_api_key_object.user is not None
# :KLUDGE: CHMiddleware does not receive the correct user when authenticating by api key.
- tag_queries(
+ tag_authentication(
user_id=personal_api_key_object.user.pk,
team_id=personal_api_key_object.user.current_team_id,
- access_method="personal_api_key",
+ access_method=AccessMethod.PERSONAL_API_KEY,
api_key_mask=personal_api_key_object.mask_value,
api_key_label=personal_api_key_object.label,
)
@@ -327,55 +331,69 @@ class PersonalAPIKeyAuthentication(authentication.BaseAuthentication):
return cls.keyword
-class TeamSecretTokenAuthentication(authentication.BaseAuthentication):
+def _extract_phs_token(request: Union[HttpRequest, Request], allow_body_token: bool = False) -> 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
+ ProjectSecretAPIKeyAuthentication (PSAK model).
"""
- Authenticates using a team secret token. Unlike a personal API key, this is not associated with a
- user and should only be used for local_evaluation and flags remote_config (not to be confused with the
- other remote_config endpoint) requests. When authenticated, this returns a "synthetic"
- TeamSecretTokenUser object that has the team set. This allows us to use the existing permissioning
- system for local_evaluation and flags remote_config requests.
+ if "authorization" in request.headers:
+ authorization_match = re.match(r"^Bearer\s+(.+)$", request.headers["authorization"])
+ if authorization_match:
+ token = authorization_match.group(1).strip()
+ if _SECRET_API_KEY_RE.match(token):
+ return token
- 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.
+ 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
+
+
+class TeamSecretTokenUser(SyntheticUser):
+ """
+ Synthetic user returned by TeamSecretTokenAuthentication when authenticating
+ via the legacy team-level Team.secret_api_token field.
"""
- keyword = "Bearer"
+ def __init__(self, team):
+ super().__init__(team, distinct_id=f"team-secret-token-{team.id}")
- @classmethod
- def find_secret_api_token(
- cls,
- request: Union[HttpRequest, Request],
- ) -> Optional[str]:
- """Try to find team secret token in request and return it"""
- if "authorization" in request.headers:
- authorization_match = re.match(rf"^{cls.keyword}\s+(.+)$", request.headers["authorization"])
- if authorization_match:
- token = authorization_match.group(1).strip()
- if _SECRET_API_KEY_RE.match(token):
- return token
- # Wrap HttpRequest in DRF Request if needed
- if not isinstance(request, Request):
- request = Request(request)
+class TeamSecretTokenAuthentication(authentication.BaseAuthentication):
+ """
+ Authenticates using the legacy team-level Team.secret_api_token field.
- data = request.data
+ This is not a ProjectSecretAPIKey (PSAK) model authenticator — it validates the
+ `phs_*` token against the legacy per-team secret stored on the Team row. It's
+ intended for endpoints that were gated before PSAK existed.
- if data and "secret_api_key" in data:
- secret_api_key = data["secret_api_key"]
- if isinstance(secret_api_key, str) and _SECRET_API_KEY_RE.match(secret_api_key):
- SECRET_API_KEY_BODY_COUNTER.inc()
- return secret_api_key
+ When authenticated, returns a synthetic TeamSecretTokenUser with the team
+ attached, so downstream permission code can resolve team context without a
+ real User.
- return None
+ 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).
+ """
+
+ keyword = "Bearer"
def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
- secret_api_token = self.find_secret_api_token(request)
+ secret_api_token = _extract_phs_token(request, allow_body_token=True)
if not secret_api_token:
return None
- # get the team from the team secret token
try:
Team = apps.get_model(app_label="posthog", model_name="Team")
team = Team.objects.get_team_from_cache_or_secret_api_token(secret_api_token)
@@ -383,8 +401,12 @@ class TeamSecretTokenAuthentication(authentication.BaseAuthentication):
if team is None:
return None
- # The team secret token is not associated with a user, so we create a TeamSecretTokenUser
- # and attach the team. The team is the important part here.
+ tag_authentication(
+ user_id=None,
+ team_id=team.id,
+ access_method=AccessMethod.TEAM_SECRET_TOKEN,
+ )
+
return (TeamSecretTokenUser(team), None)
except Team.DoesNotExist:
return None
@@ -394,22 +416,66 @@ class TeamSecretTokenAuthentication(authentication.BaseAuthentication):
return cls.keyword
-class TeamSecretTokenUser:
+class ProjectSecretAPIKeyUser(SyntheticUser):
"""
- A "synthetic" user object returned by the TeamSecretTokenAuthentication when authenticating with a team secret token.
+ Synthetic user returned by ProjectSecretAPIKeyAuthentication. Carries the
+ backing ProjectSecretAPIKey so APIScopePermission can read its scopes.
"""
- def __init__(self, team):
- self.team = team
- self.current_team_id = team.id
- self.is_authenticated = True
- self.pk = -1
+ def __init__(self, project_secret_api_key):
+ super().__init__(
+ project_secret_api_key.team,
+ distinct_id=f"psak-{project_secret_api_key.team_id}-{project_secret_api_key.id}",
+ )
+ self.project_secret_api_key = project_secret_api_key
- def has_perm(self, perm, obj=None):
- return False
+ def readable_system_table_access_scopes(self) -> set[str]:
+ return {scope.split(":", 1)[0] for scope in self.project_secret_api_key.scopes or [] if ":" in scope}
- def has_module_perms(self, app_label):
- return False
+
+class ProjectSecretAPIKeyAuthentication(authentication.BaseAuthentication):
+ """
+ Authenticates a ProjectSecretAPIKey (PSAK) model record via its SHA256 hash.
+
+ Does NOT fall back to Team.secret_api_token — that's TeamSecretTokenAuthentication.
+ Intended for endpoints that enforce PSAK scopes via APIScopePermission.
+
+ PSAK scopes grant project-wide access within the scoped resource type. They do
+ not honor object-level access controls like per-resource RBAC restrictions.
+ """
+
+ keyword = "Bearer"
+
+ def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
+ token = _extract_phs_token(request, allow_body_token=False)
+ if not token:
+ return None
+
+ psak = find_project_secret_api_key(token)
+ if psak is None:
+ return None
+
+ now = timezone.now()
+ if psak.last_used_at is None or (now - psak.last_used_at > timedelta(hours=1)):
+ # Use .update() to bypass ModelActivityMixin save hooks and avoid
+ # activity-log noise / Redis cache invalidation on every request.
+ ProjectSecretAPIKey.objects.filter(pk=psak.pk).update(last_used_at=now)
+
+ self.project_secret_api_key = psak
+
+ tag_authentication(
+ user_id=None,
+ team_id=psak.team_id,
+ access_method=AccessMethod.PROJECT_SECRET_API_KEY,
+ api_key_mask=psak.mask_value,
+ api_key_label=psak.label,
+ )
+
+ return (ProjectSecretAPIKeyUser(psak), None)
+
+ @classmethod
+ def authenticate_header(cls, request) -> str:
+ return cls.keyword
class JwtAuthentication(authentication.BaseAuthentication):
@@ -602,10 +668,10 @@ class IDJagAccessTokenAuthentication(authentication.BaseAuthentication):
self.scopes = str(claims.get("scope") or "").split()
self.organization_id = organization_id
- tag_queries(
+ tag_authentication(
user_id=user.pk,
team_id=user.current_team_id,
- access_method="id_jag",
+ access_method=AccessMethod.ID_JAG,
)
return user, None
@@ -789,10 +855,10 @@ class OAuthAccessTokenAuthentication(authentication.BaseAuthentication):
self.access_token = access_token
- tag_queries(
+ tag_authentication(
user_id=access_token.user.pk,
team_id=access_token.user.current_team_id,
- access_method="oauth",
+ access_method=AccessMethod.OAUTH,
)
return access_token.user, None
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 67a6bd1af76c..97a49d4597e4 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -28,6 +28,22 @@ class AccessMethod(StrEnum):
OAUTH = "oauth"
SHARING_TOKEN = "sharing_token"
ID_JAG = "id_jag"
+ PROJECT_SECRET_API_KEY = "project_secret_api_key"
+ TEAM_SECRET_TOKEN = "team_secret_token"
+
+
+# OAuth and sharing-token deliberately excluded: OAuth is user-consented, sharing-token is public read-only.
+_API_KEY_ACCESS_METHODS: frozenset[AccessMethod] = frozenset(
+ {
+ AccessMethod.PERSONAL_API_KEY,
+ AccessMethod.PROJECT_SECRET_API_KEY,
+ AccessMethod.TEAM_SECRET_TOKEN,
+ }
+)
+
+
+def is_api_key_access_method(access_method: AccessMethod | str | None) -> bool:
+ return access_method in _API_KEY_ACCESS_METHODS
class Product(StrEnum):
@@ -531,6 +547,24 @@ def tag_queries(**kwargs) -> None:
query_tags.set(updated_tags)
+def tag_authentication(
+ *,
+ access_method: AccessMethod,
+ team_id: int | None,
+ user_id: int | None = None,
+ api_key_mask: str | None = None,
+ api_key_label: str | None = None,
+) -> None:
+ """Single funnel for authenticator query tagging — add new auth tags here, not in each authenticator."""
+ tag_queries(
+ user_id=user_id,
+ team_id=team_id,
+ access_method=access_method,
+ api_key_mask=api_key_mask,
+ api_key_label=api_key_label,
+ )
+
+
def tag_contains_user_hogql() -> None:
"""Mark the current query as embedding a user-supplied HogQL string; used to separate user vs platform errors in system.query_log.
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 71745ac44dc1..405af05e9b48 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -158,6 +158,7 @@ from posthog.models.group_type_mapping import get_group_types_for_project
from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team, WeekStartDay
from posthog.rbac.user_access_control import NO_ACCESS_LEVEL, UserAccessControl
+from posthog.synthetic_user import SyntheticUser
from products.data_tools.backend.models.join import DataWarehouseJoin
from products.data_warehouse.backend.sync_status import get_warehouse_sync_warnings
@@ -196,7 +197,7 @@ class HogQLDatabaseSources:
build phase runs without any queries."""
team: "Team"
- user: Optional["User"]
+ user: Optional["User | SyntheticUser"]
connection_id: str | None
modifiers: HogQLQueryModifiers
is_managed_viewset_enabled: bool
@@ -371,19 +372,22 @@ def build_database_root_node(*, include_posthog_tables: bool = True) -> TableNod
def _compute_system_table_access_decision(
- team: "Team", user: Optional["User"]
+ team: "Team", user: Optional["User | SyntheticUser"]
) -> tuple[Optional["UserAccessControl"], set[str]]:
"""Decide which scoped system tables to hide, doing the access-control I/O here so the build phase
can apply the result without querying. Returns the warmed UserAccessControl (whose membership/role/
access-control caches make later reads query-free) and the system-node table names to remove."""
system_children = SystemTables().children
- # No user: remove every access-controlled system table.
- if user is None:
+ # Anonymous or synthetic principal: keep only access-controlled tables its scopes cover (none for anonymous / team token).
+ if user is None or isinstance(user, SyntheticUser):
+ readable_scopes = user.readable_system_table_access_scopes() if user is not None else set()
return None, {
name
for name, table_node in system_children.items()
- if isinstance(table_node.table, PostgresTable) and table_node.table.access_scope is not None
+ if isinstance(table_node.table, PostgresTable)
+ and table_node.table.access_scope is not None
+ and table_node.table.access_scope not in readable_scopes
}
user_access_control = UserAccessControl(user=user, team=team)
@@ -922,7 +926,7 @@ class Database(BaseModel):
team_id: int | None = None,
*,
team: Optional["Team"] = None,
- user: Optional["User"] = None,
+ user: Optional["User | SyntheticUser"] = None,
modifiers: HogQLQueryModifiers | None = None,
timings: HogQLTimings | None = None,
connection_id: str | None = None,
@@ -945,7 +949,7 @@ class Database(BaseModel):
team_id: int | None = None,
*,
team: Optional["Team"] = None,
- user: Optional["User"] = None,
+ user: Optional["User | SyntheticUser"] = None,
modifiers: HogQLQueryModifiers | None = None,
timings: HogQLTimings | None = None,
connection_id: str | None = None,
diff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.py
index d56442c8af35..753b8e940189 100644
--- a/posthog/hogql/database/test/test_database.py
+++ b/posthog/hogql/database/test/test_database.py
@@ -22,6 +22,7 @@ from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import (
ROOT_TABLES__DO_NOT_ADD_ANY_MORE,
Database,
+ _compute_system_table_access_decision,
_preload_active_external_data_schemas,
build_database_root_node,
get_data_warehouse_table_name,
@@ -2865,3 +2866,56 @@ class TestDatabase(BaseTest, QueryMatchingTest):
database = Database.create_for(team=self.team)
persons = database.get_table("persons")
assert "ext_data" not in persons.fields
+
+ def test_create_for_with_synthetic_user_skips_user_rbac(self):
+ from posthog.auth import ProjectSecretAPIKeyUser
+ from posthog.models.project_secret_api_key import ProjectSecretAPIKey
+
+ psak = ProjectSecretAPIKey.objects.create(
+ team=self.team,
+ label="rbac-shortcircuit",
+ secure_value="sha256$" + "f" * 64,
+ scopes=["endpoint:read"],
+ )
+ synthetic_user = ProjectSecretAPIKeyUser(psak)
+
+ captured: dict = {}
+
+ def spy(team, user):
+ result = _compute_system_table_access_decision(team, user)
+ captured["result"] = result
+ return result
+
+ with (
+ patch("posthoganalytics.feature_enabled", return_value=True),
+ patch("posthog.hogql.database.database._compute_system_table_access_decision", side_effect=spy) as decision,
+ ):
+ Database.create_for(team=self.team, user=synthetic_user)
+
+ decision.assert_called_once()
+ user_access_control, denied = captured["result"]
+ # No per-user access control, but the endpoint:read scope keeps the endpoint-scoped
+ # system tables; other scoped tables (e.g. feature_flags) stay hidden.
+ assert user_access_control is None
+ assert "data_modeling_endpoints" not in denied
+ assert "data_modeling_endpoint_versions" not in denied
+ assert "feature_flags" in denied
+
+ def test_create_for_with_real_user_uses_user_rbac(self):
+ captured: dict = {}
+
+ def spy(team, user):
+ result = _compute_system_table_access_decision(team, user)
+ captured["result"] = result
+ return result
+
+ with (
+ patch("posthoganalytics.feature_enabled", return_value=True),
+ patch("posthog.hogql.database.database._compute_system_table_access_decision", side_effect=spy) as decision,
+ ):
+ Database.create_for(team=self.team, user=self.user)
+
+ decision.assert_called_once()
+ user_access_control, _denied = captured["result"]
+ # A real user gets per-user access control computed rather than the anonymous all-deny path.
+ assert user_access_control is not None
diff --git a/posthog/models/project_secret_api_key.py b/posthog/models/project_secret_api_key.py
index 9198104f5901..6e0aae0e4a33 100644
--- a/posthog/models/project_secret_api_key.py
+++ b/posthog/models/project_secret_api_key.py
@@ -1,10 +1,12 @@
+from typing import Optional
+
from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.utils import timezone
from posthog.models.activity_logging.model_activity import ModelActivityMixin
-from .utils import generate_random_token
+from .utils import generate_random_token, hash_key_value
class ProjectSecretAPIKey(ModelActivityMixin, models.Model):
@@ -12,6 +14,9 @@ class ProjectSecretAPIKey(ModelActivityMixin, models.Model):
API key tied to a project. Behaves in the same way as a PersonalAPIKey,
but isn't tied to a single user.
+ Scopes grant project-wide access within their resource type. PSAKs do not
+ honor object-level access controls like per-resource RBAC restrictions.
+
Intended to be used only by endpoints that should be hit programmatically
and that need to remain accessible even when a user leaves a project.
@@ -48,3 +53,11 @@ class ProjectSecretAPIKey(ModelActivityMixin, models.Model):
db_table = "posthog_projectsecretapikey"
indexes = [models.Index(fields=["team", "created_at"])]
constraints = [models.UniqueConstraint(fields=["team", "label"], name="unique_team_label")]
+
+
+def find_project_secret_api_key(token: str) -> Optional["ProjectSecretAPIKey"]:
+ secure_value = hash_key_value(token)
+ try:
+ return ProjectSecretAPIKey.objects.select_related("team").get(secure_value=secure_value)
+ except ProjectSecretAPIKey.DoesNotExist:
+ return None
diff --git a/posthog/permissions.py b/posthog/permissions.py
index 390640ea4e38..c7d5ce75868e 100644
--- a/posthog/permissions.py
+++ b/posthog/permissions.py
@@ -18,6 +18,7 @@ from posthog.auth import (
IDJagAccessTokenAuthentication,
OAuthAccessTokenAuthentication,
PersonalAPIKeyAuthentication,
+ ProjectSecretAPIKeyAuthentication,
SessionAuthentication,
SharingAccessTokenAuthentication,
SharingPasswordProtectedAuthentication,
@@ -214,8 +215,14 @@ class TeamMemberAccessPermission(BasePermission):
message = "You don't have access to the project."
def has_permission(self, request, view) -> bool:
+ if is_authenticated_via_project_secret_api_key(request):
+ psak = request.successful_authenticator.project_secret_api_key
+ try:
+ return view.team.id == psak.team_id
+ except (AttributeError, KeyError, Team.DoesNotExist):
+ return False
+
if is_authenticated_via_team_secret_token(request):
- # Ignore the team check for team secret tokens. It's handled by the TeamSecretTokenPermission
return True
try:
@@ -233,6 +240,14 @@ def is_authenticated_via_team_secret_token(request: Request) -> bool:
return isinstance(request.successful_authenticator, TeamSecretTokenAuthentication)
+def is_authenticated_via_project_secret_api_key(request: Request) -> bool:
+ return isinstance(request.successful_authenticator, ProjectSecretAPIKeyAuthentication)
+
+
+def is_service_auth(request: Request) -> bool:
+ return is_authenticated_via_team_secret_token(request) or is_authenticated_via_project_secret_api_key(request)
+
+
def _is_request_for_team_secret_token_secured_endpoint(request: Request) -> bool:
return bool(
request.resolver_match
@@ -448,6 +463,7 @@ class ScopeBasePermission(BasePermission):
read_actions: list[str] = ["list", "retrieve"]
scope_object_read_actions: list[str] = []
scope_object_write_actions: list[str] = []
+ psak_allowed_actions: list[str] = []
def _get_scope_object(self, request, view) -> APIScopeObjectOrNotSupported:
if not getattr(view, "scope_object", None):
@@ -510,11 +526,14 @@ class APIScopePermission(ScopeBasePermission):
# API Scopes apply to PersonalAPIKeyAuthentication and OAuthAccessTokenAuthentication
- if isinstance(request.successful_authenticator, PersonalAPIKeyAuthentication):
- key_scopes = request.successful_authenticator.personal_api_key.scopes
- elif isinstance(request.successful_authenticator, OAuthAccessTokenAuthentication):
+ authenticator = request.successful_authenticator
+ is_psak = isinstance(authenticator, ProjectSecretAPIKeyAuthentication)
+
+ if isinstance(authenticator, PersonalAPIKeyAuthentication):
+ key_scopes = authenticator.personal_api_key.scopes
+ elif isinstance(authenticator, OAuthAccessTokenAuthentication):
# OAuth tokens store scopes as space-separated string
- token_scope_string = request.successful_authenticator.access_token.scope
+ token_scope_string = authenticator.access_token.scope
key_scopes = token_scope_string.split() if token_scope_string else []
# OAuth tokens with no scopes should not have access
if not key_scopes:
@@ -525,6 +544,12 @@ class APIScopePermission(ScopeBasePermission):
if not key_scopes:
self.message = "ID-JAG access token has no scopes and cannot access this resource"
return False
+ elif is_psak:
+ psak_allowed_actions = getattr(view, "psak_allowed_actions", self.psak_allowed_actions)
+ if self._get_action(request, view) not in psak_allowed_actions:
+ self.message = "This action does not support project secret API key access"
+ return False
+ key_scopes = authenticator.project_secret_api_key.scopes or []
else:
# Session (and other non-token) auth normally bypasses API-scope checks — scopes
# are a PAK/OAuth concept; logged-in users are gated by team membership + access
@@ -547,7 +572,10 @@ class APIScopePermission(ScopeBasePermission):
self.message = "This action does not support personal API key access"
return False
- self.check_team_and_org_permissions(request, view)
+ if is_psak:
+ self._check_project_secret_api_key_team(request, view)
+ else:
+ self.check_team_and_org_permissions(request, view)
# `*` is the "Full access to all scopes" consent option; INTERNAL viewsets
# are programmatic-only and must not be reachable via user-consented tokens.
@@ -575,6 +603,16 @@ class APIScopePermission(ScopeBasePermission):
return True
+ def _check_project_secret_api_key_team(self, request, view) -> None:
+ psak = request.successful_authenticator.project_secret_api_key
+ try:
+ team_id = view.team.id
+ except (AttributeError, KeyError, Team.DoesNotExist):
+ raise PermissionDenied("Project secret API keys are only supported on project-based endpoints.")
+
+ if team_id != psak.team_id:
+ raise PermissionDenied(f"API key does not have access to the requested project: ID {team_id}.")
+
def check_team_and_org_permissions(self, request, view) -> None:
scope_object = self._get_scope_object(request, view)
@@ -702,6 +740,13 @@ class AccessControlPermission(ScopeBasePermission):
def has_object_permission(self, request, view, object) -> bool:
# At this level we are checking an individual resource - this could be a project or a lower level item like a Dashboard
+
+ # Service credentials (TST, PSAK) are synthetic users UserAccessControl can't evaluate.
+ # They're gated by API scope + project membership, so scopes grant project-wide access
+ # within that resource type and object-level RBAC restrictions don't apply.
+ if is_service_auth(request):
+ return True
+
# NOTE: If the object is a Team then we shortcircuit here and create a UAC
# Reason being that there is a loop from view.user_access_control -> view.team -> view.user_access_control
if isinstance(object, Team):
@@ -731,8 +776,7 @@ class AccessControlPermission(ScopeBasePermission):
# Primarily we are checking the user's access to the parent resource type (i.e. project, organization)
# as well as enforcing any global restrictions (e.g. generically only editing of a flag is allowed)
- if is_authenticated_via_team_secret_token(request):
- # Ignore the team check for team secret tokens. It's handled by the TeamSecretTokenPermission
+ if is_service_auth(request):
return True
# Check if the endpoint requires a current team to be set on the user
@@ -853,8 +897,11 @@ class PostHogFeatureFlagPermission(BasePermission):
class TeamSecretTokenPermission(BasePermission):
"""
- Controls access to the local_evaluation and remote_config endpoints when authenticated via a team secret token.
- Also validates that the authenticated team matches the resolved team (analogous to TeamMemberAccessPermission for personal keys).
+ Controls access to the local_evaluation and remote_config endpoints when authenticated via
+ the legacy team-level Team.secret_api_token (see TeamSecretTokenAuthentication).
+
+ Also validates that the authenticated team matches the resolved team (analogous to
+ TeamMemberAccessPermission for personal keys).
"""
def has_permission(self, request, view) -> bool:
@@ -870,7 +917,7 @@ class TeamSecretTokenPermission(BasePermission):
authenticated_team = request.user.team # From TeamSecretTokenUser
try:
resolved_team = view.team # From routing logic (may use project_api_key override)
- except (AttributeError, Team.DoesNotExist):
+ except (AttributeError, KeyError, Team.DoesNotExist):
# If team resolution fails, let it be handled as a 404 in the viewset
return True
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index f21c492c1c60..bf93c48207d7 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -12,7 +12,7 @@ from prometheus_client import Counter
from rest_framework.throttling import SimpleRateThrottle, UserRateThrottle
from statshog.defaults.django import statsd
-from posthog.auth import PersonalAPIKeyAuthentication
+from posthog.auth import PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthentication
from posthog.event_usage import report_user_action
from posthog.exceptions_capture import capture_exception
from posthog.metrics import LABEL_PATH, LABEL_ROUTE, LABEL_TEAM_ID
@@ -382,6 +382,46 @@ class PersonalApiKeyOrUserRateThrottle(PersonalApiKeyRateThrottle):
return self._allow_request_internal(request, view, personal_api_key_only=False)
+class PersonalOrProjectSecretApiKeyRateThrottle(PersonalApiKeyRateThrottle):
+ """
+ Rate limit personal API key and project secret API key (PSAK) requests, keyed per key.
+
+ PSAK requests carry no personal API key, so they slip past PersonalApiKeyRateThrottle's
+ personal_api_key_only gate; this also throttles them. Session/web users still bypass.
+ """
+
+ def allow_request(self, request, view):
+ if isinstance(request.successful_authenticator, ProjectSecretAPIKeyAuthentication):
+ return self._allow_request_internal(request, view, personal_api_key_only=False)
+ return super().allow_request(request, view)
+
+ def get_cache_key(self, request, view):
+ auth = request.successful_authenticator
+ if isinstance(auth, ProjectSecretAPIKeyAuthentication):
+ return self.cache_format % {"scope": self.scope, "ident": f"psak:{auth.project_secret_api_key.id}"}
+ return super().get_cache_key(request, view)
+
+
+class ProjectSecretApiKeyTeamRateThrottle(PersonalApiKeyRateThrottle):
+ """
+ Per-team aggregate throttle for project secret API key (PSAK) requests.
+
+ Stack alongside a per-key throttle (PersonalOrProjectSecretApiKeyRateThrottle) so a project's
+ total PSAK load is capped regardless of how many keys it mints — the per-key throttle gives
+ each credential a fair budget, this caps the sum. Only PSAK requests count; any other auth
+ (personal key, OAuth, session) bypasses and is left to its own throttles.
+ """
+
+ def allow_request(self, request, view):
+ if isinstance(request.successful_authenticator, ProjectSecretAPIKeyAuthentication):
+ return self._allow_request_internal(request, view, personal_api_key_only=False)
+ return True
+
+ def get_cache_key(self, request, view):
+ team_id = request.successful_authenticator.project_secret_api_key.team_id
+ return self.cache_format % {"scope": self.scope, "ident": f"psak-team:{team_id}"}
+
+
class ClickHouseBurstRateThrottle(PersonalApiKeyRateThrottle):
# Throttle class that's a bit more aggressive and is used specifically on endpoints that hit ClickHouse
# Intended to block quick bursts of requests, per project
diff --git a/posthog/synthetic_user.py b/posthog/synthetic_user.py
new file mode 100644
index 000000000000..e22e8222c643
--- /dev/null
+++ b/posthog/synthetic_user.py
@@ -0,0 +1,41 @@
+"""Lives outside posthog.auth to avoid a circular import when imported by posthog.hogql."""
+
+from typing import Optional
+
+
+class SyntheticUser:
+ """Tagged base class for non-real principals authenticated via service tokens.
+
+ Behavior (subclasses may override `readable_system_table_access_scopes`):
+ * `Database.create_for` hides RBAC-scoped system tables the principal's
+ scopes don't cover (`readable_system_table_access_scopes`); the base hides all.
+ * `has_perm` / `has_module_perms` always return False; Django
+ permission checks against a SyntheticUser silently deny.
+ * `id` is None; do not use it as a foreign key. Use `current_team_id`.
+ """
+
+ email: Optional[str] = None
+ is_staff: bool = False
+ is_superuser: bool = False
+ is_active: bool = True
+ is_anonymous: bool = False
+
+ def __init__(self, team, distinct_id: str):
+ self.team = team
+ self.current_team_id = team.id
+ self.is_authenticated = True
+ self.pk = -1
+ self.id: Optional[int] = None
+ self.distinct_id = distinct_id
+ self.groups: list = []
+ self.user_permissions: list = []
+
+ def has_perm(self, perm, obj=None):
+ return False
+
+ def has_module_perms(self, app_label):
+ return False
+
+ def readable_system_table_access_scopes(self) -> set[str]:
+ """Resource scopes whose access-controlled system tables this principal may read (empty = none)."""
+ return set()
diff --git a/posthog/test/test_permissions.py b/posthog/test/test_permissions.py
index d8ac6464ea2d..a871abe47931 100644
--- a/posthog/test/test_permissions.py
+++ b/posthog/test/test_permissions.py
@@ -2,16 +2,17 @@ import json
from datetime import timedelta
from posthog.test.base import BaseTest
-from unittest.mock import Mock, patch
+from unittest.mock import Mock, PropertyMock, patch
from django.conf import settings
-from django.test import override_settings
+from django.test import SimpleTestCase, override_settings
from django.utils import timezone
from parameterized import parameterized
from rest_framework.test import APIRequestFactory
from posthog.api.oauth.test_dcr import generate_rsa_key
+from posthog.auth import PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthentication, TeamSecretTokenAuthentication
from posthog.constants import AvailableFeature
from posthog.models import Organization, Team, User
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
@@ -419,6 +420,121 @@ class TestTeamSecretTokenPermission(BaseTest):
self.assertFalse(result)
+class TestProjectSecretAPIKeyAPIScopePermission(SimpleTestCase):
+ def setUp(self):
+ from posthog.permissions import APIScopePermission
+
+ self.permission = APIScopePermission()
+
+ def _make_psak_request(self, scopes=("endpoint:read",), team_id=1):
+ from posthog.auth import ProjectSecretAPIKeyAuthentication
+
+ request = Mock()
+ request.method = "POST"
+
+ authenticator = Mock(spec=ProjectSecretAPIKeyAuthentication)
+ psak = Mock()
+ psak.team_id = team_id
+ psak.scopes = list(scopes)
+ authenticator.project_secret_api_key = psak
+ request.successful_authenticator = authenticator
+ return request, psak
+
+ def test_default_deny_when_view_omits_psak_allowed_actions(self):
+ request, _ = self._make_psak_request()
+
+ view = Mock(spec=[])
+ view.action = "run"
+ view.scope_object = "endpoint"
+
+ self.assertFalse(self.permission.has_permission(request, view))
+ self.assertIn("does not support project secret API key", self.permission.message)
+
+ def test_team_check_attribute_error_denies(self):
+ from rest_framework.exceptions import PermissionDenied
+
+ request, _ = self._make_psak_request()
+
+ class NoTeamView:
+ @property
+ def team(self):
+ raise AttributeError("view has no team attribute")
+
+ with self.assertRaises(PermissionDenied) as ctx:
+ self.permission._check_project_secret_api_key_team(request, NoTeamView())
+
+ self.assertIn("only supported on project-based endpoints", str(ctx.exception.detail))
+
+ def test_team_check_key_error_denies(self):
+ from rest_framework.exceptions import PermissionDenied
+
+ request, _ = self._make_psak_request()
+
+ class NoTeamKwargView:
+ @property
+ def team(self):
+ raise KeyError("team_id")
+
+ with self.assertRaises(PermissionDenied) as ctx:
+ self.permission._check_project_secret_api_key_team(request, NoTeamKwargView())
+
+ self.assertIn("only supported on project-based endpoints", str(ctx.exception.detail))
+
+ def test_team_check_does_not_exist_denies(self):
+ from rest_framework.exceptions import PermissionDenied
+
+ from posthog.models.team import Team
+
+ request, _ = self._make_psak_request()
+
+ class StaleTeamView:
+ @property
+ def team(self):
+ raise Team.DoesNotExist
+
+ with self.assertRaises(PermissionDenied) as ctx:
+ self.permission._check_project_secret_api_key_team(request, StaleTeamView())
+
+ self.assertIn("only supported on project-based endpoints", str(ctx.exception.detail))
+
+ def test_allows_read_action_with_matching_scope_and_team(self):
+ request, _ = self._make_psak_request(scopes=("endpoint:read",), team_id=1)
+
+ view = Mock(spec=[])
+ view.action = "run"
+ view.scope_object = "endpoint"
+ view.scope_object_read_actions = ["run"]
+ view.psak_allowed_actions = ["run"]
+ view.team = Mock(id=1)
+
+ self.assertTrue(self.permission.has_permission(request, view))
+
+ def test_denies_write_action_with_only_read_scope(self):
+ request, _ = self._make_psak_request(scopes=("endpoint:read",), team_id=1)
+
+ view = Mock(spec=[])
+ view.action = "create"
+ view.scope_object = "endpoint"
+ view.psak_allowed_actions = ["create"]
+ view.team = Mock(id=1)
+
+ self.assertFalse(self.permission.has_permission(request, view))
+ self.assertIn("missing required scope 'endpoint:write'", self.permission.message)
+
+ def test_team_check_denies_when_psak_team_differs(self):
+ from rest_framework.exceptions import PermissionDenied
+
+ request, _ = self._make_psak_request(team_id=1)
+
+ view = Mock(spec=[])
+ view.team = Mock(id=999)
+
+ with self.assertRaises(PermissionDenied) as ctx:
+ self.permission._check_project_secret_api_key_team(request, view)
+
+ self.assertIn("does not have access to the requested project", str(ctx.exception.detail))
+
+
class TestTeamMemberAccessPermission(BaseTest):
"""Direct unit tests for TeamMemberAccessPermission.has_permission method"""
@@ -428,7 +544,7 @@ class TestTeamMemberAccessPermission(BaseTest):
self.permission = TeamMemberAccessPermission()
- def _create_mock_request(self, authenticator_class=None, user=None):
+ def _create_mock_request(self, authenticator_class=None, user=None, psak_team_id=None):
"""Helper to create a mock request with specified authenticator"""
request = Mock()
@@ -436,6 +552,8 @@ class TestTeamMemberAccessPermission(BaseTest):
mock_authenticator = Mock()
if authenticator_class:
mock_authenticator.__class__ = authenticator_class
+ if psak_team_id is not None:
+ mock_authenticator.project_secret_api_key = Mock(team_id=psak_team_id)
request.successful_authenticator = mock_authenticator
# Set user if provided
@@ -449,8 +567,7 @@ class TestTeamMemberAccessPermission(BaseTest):
view = Mock()
if raise_exception:
- # Configure the mock to raise the exception when team is accessed
- view.team = Mock(side_effect=raise_exception)
+ type(view).team = PropertyMock(side_effect=raise_exception)
else:
view.team = team
@@ -476,8 +593,6 @@ class TestTeamMemberAccessPermission(BaseTest):
def test_has_permission_with_team_secret_token_authenticator(self):
"""Should return True when using TeamSecretTokenAuthentication"""
- from posthog.auth import TeamSecretTokenAuthentication
-
request = self._create_mock_request(authenticator_class=TeamSecretTokenAuthentication)
view = self._create_mock_view()
@@ -485,11 +600,35 @@ class TestTeamMemberAccessPermission(BaseTest):
self.assertTrue(result)
+ def test_has_permission_with_project_secret_api_key_matching_team(self):
+ request = self._create_mock_request(
+ authenticator_class=ProjectSecretAPIKeyAuthentication,
+ psak_team_id=1,
+ )
+ view = self._create_mock_view(team=self._create_mock_team(team_id=1))
+
+ self.assertTrue(self.permission.has_permission(request, view))
+
+ def test_has_permission_with_project_secret_api_key_different_team(self):
+ request = self._create_mock_request(
+ authenticator_class=ProjectSecretAPIKeyAuthentication,
+ psak_team_id=1,
+ )
+ view = self._create_mock_view(team=self._create_mock_team(team_id=2))
+
+ self.assertFalse(self.permission.has_permission(request, view))
+
+ def test_has_permission_with_project_secret_api_key_missing_team(self):
+ request = self._create_mock_request(
+ authenticator_class=ProjectSecretAPIKeyAuthentication,
+ psak_team_id=1,
+ )
+ view = self._create_mock_view(raise_exception=Team.DoesNotExist("Team not found"))
+
+ self.assertFalse(self.permission.has_permission(request, view))
+
def test_has_permission_with_non_team_secret_token_authenticator_and_valid_membership(self):
"""Should return True when not using project secret auth and user has valid membership"""
- from posthog.auth import PersonalAPIKeyAuthentication
- from posthog.models.organization import OrganizationMembership
-
team = self._create_mock_team()
user_permissions = self._create_mock_user_permissions(
effective_membership_level=OrganizationMembership.Level.MEMBER
@@ -504,8 +643,6 @@ class TestTeamMemberAccessPermission(BaseTest):
def test_has_permission_with_non_team_secret_token_authenticator_and_no_membership(self):
"""Should return False when not using project secret auth and user has no membership"""
- from posthog.auth import PersonalAPIKeyAuthentication
-
team = self._create_mock_team()
user_permissions = self._create_mock_user_permissions(effective_membership_level=None)
@@ -518,8 +655,6 @@ class TestTeamMemberAccessPermission(BaseTest):
def test_has_permission_with_team_does_not_exist_exception(self):
"""Should return True when view.team raises Team.DoesNotExist"""
- from posthog.auth import PersonalAPIKeyAuthentication
-
request = self._create_mock_request(authenticator_class=PersonalAPIKeyAuthentication)
view = self._create_mock_view(raise_exception=Team.DoesNotExist("Team not found"))
@@ -529,9 +664,6 @@ class TestTeamMemberAccessPermission(BaseTest):
def test_has_permission_with_admin_membership(self):
"""Should return True when user has admin membership level"""
- from posthog.auth import PersonalAPIKeyAuthentication
- from posthog.models.organization import OrganizationMembership
-
team = self._create_mock_team()
user_permissions = self._create_mock_user_permissions(
effective_membership_level=OrganizationMembership.Level.ADMIN
diff --git a/posthog/test/test_rate_limit.py b/posthog/test/test_rate_limit.py
index d5d5aed7fbf6..e63033660784 100644
--- a/posthog/test/test_rate_limit.py
+++ b/posthog/test/test_rate_limit.py
@@ -15,6 +15,7 @@ from rest_framework import status
from posthog import models, rate_limit
from posthog.api.test.test_team import create_team
from posthog.api.test.test_user import create_user
+from posthog.auth import ProjectSecretAPIKeyAuthentication
from posthog.models import Team
from posthog.models.instance_setting import override_instance_config
from posthog.models.personal_api_key import PersonalAPIKey
@@ -802,3 +803,61 @@ class TestUserAPI(APIBaseTest):
self.assertEqual(num_requests, 5)
self.assertEqual(duration, 3600)
+
+
+class _PSAKThrottleForTest(rate_limit.PersonalOrProjectSecretApiKeyRateThrottle):
+ scope = "test_psak"
+ rate = "100/minute"
+
+
+class TestPersonalOrProjectSecretApiKeyRateThrottle(APIBaseTest):
+ def _psak_request(self, key_id=1):
+ auth = ProjectSecretAPIKeyAuthentication()
+ auth.project_secret_api_key = Mock(id=key_id)
+ return Mock(successful_authenticator=auth)
+
+ def test_psak_requests_do_not_bypass_throttle(self):
+ # PSAK carries no personal API key; the throttle must not let it through the
+ # personal_api_key_only gate that PersonalApiKeyRateThrottle uses.
+ throttle = _PSAKThrottleForTest()
+ request = self._psak_request()
+ with patch.object(throttle, "_allow_request_internal", return_value=True) as spy:
+ throttle.allow_request(request, Mock())
+ spy.assert_called_once_with(request, ANY, personal_api_key_only=False)
+
+ def test_non_psak_request_uses_personal_api_key_only_gate(self):
+ throttle = _PSAKThrottleForTest()
+ request = Mock(successful_authenticator=Mock())
+ with patch.object(throttle, "_allow_request_internal", return_value=True) as spy:
+ throttle.allow_request(request, Mock())
+ spy.assert_called_once_with(ANY, ANY, personal_api_key_only=True)
+
+ def test_psak_requests_use_per_key_cache_bucket(self):
+ self.assertTrue(_PSAKThrottleForTest().get_cache_key(self._psak_request(key_id=42), Mock()).endswith("psak:42"))
+
+
+class _PSAKTeamThrottleForTest(rate_limit.ProjectSecretApiKeyTeamRateThrottle):
+ scope = "test_psak_team"
+ rate = "100/minute"
+
+
+class TestProjectSecretApiKeyTeamRateThrottle(APIBaseTest):
+ def _psak_request(self, team_id=7):
+ auth = ProjectSecretAPIKeyAuthentication()
+ auth.project_secret_api_key = Mock(team_id=team_id)
+ return Mock(successful_authenticator=auth)
+
+ def test_psak_request_is_throttled(self):
+ throttle = _PSAKTeamThrottleForTest()
+ with patch.object(throttle, "_allow_request_internal", return_value=True) as spy:
+ throttle.allow_request(self._psak_request(), Mock())
+ spy.assert_called_once_with(ANY, ANY, personal_api_key_only=False)
+
+ def test_non_psak_request_bypasses(self):
+ throttle = _PSAKTeamThrottleForTest()
+ with patch.object(throttle, "_allow_request_internal") as spy:
+ self.assertTrue(throttle.allow_request(Mock(successful_authenticator=Mock()), Mock()))
+ spy.assert_not_called()
+
+ def test_cache_key_is_keyed_per_team(self):
+ self.assertIn("psak-team:7", _PSAKTeamThrottleForTest().get_cache_key(self._psak_request(team_id=7), Mock()))
diff --git a/posthog/test/test_two_factor_enforcement.py b/posthog/test/test_two_factor_enforcement.py
index b8c6b6dd53ff..b5e6ec33cf49 100644
--- a/posthog/test/test_two_factor_enforcement.py
+++ b/posthog/test/test_two_factor_enforcement.py
@@ -13,7 +13,13 @@ from django.test import RequestFactory, TestCase
from rest_framework.exceptions import PermissionDenied
from rest_framework.test import APIClient, APIRequestFactory
-from posthog.auth import PersonalAPIKeyAuthentication, SessionAuthentication, TeamSecretTokenAuthentication
+from posthog.auth import (
+ PersonalAPIKeyAuthentication,
+ ProjectSecretAPIKeyAuthentication,
+ ProjectSecretAPIKeyUser,
+ SessionAuthentication,
+ TeamSecretTokenAuthentication,
+)
from posthog.helpers.two_factor_session import (
TWO_FACTOR_ENFORCEMENT_FROM_DATE,
clear_two_factor_session_flags,
@@ -21,7 +27,9 @@ from posthog.helpers.two_factor_session import (
is_two_factor_verified_in_session,
set_two_factor_verified_in_session,
)
-from posthog.models import Organization, User
+from posthog.models import Organization, Team, User
+from posthog.models.project_secret_api_key import ProjectSecretAPIKey
+from posthog.models.utils import hash_key_value
class TestTwoFactorSessionUtils(TestCase):
@@ -438,13 +446,31 @@ class TestAPIAuthenticationTwoFactorBypass(TestCase):
result = auth.authenticate(request)
self.assertIsNone(result)
- def test_project_secret_api_key_authentication_bypasses_two_factor(self):
+ def test_team_secret_token_authentication_bypasses_two_factor(self):
auth = TeamSecretTokenAuthentication()
request = self.factory.get("/api/users/@me/")
result = auth.authenticate(request)
self.assertIsNone(result)
+ def test_project_secret_api_key_authentication_bypasses_two_factor(self):
+ org = Organization.objects.create(name="2fa-psak", enforce_2fa=True)
+ team = Team.objects.create(organization=org, name="t")
+ token = "phs_" + "p" * 35
+ ProjectSecretAPIKey.objects.create(
+ team=team, label="2fa", secure_value=hash_key_value(token), scopes=["endpoint:read"]
+ )
+
+ auth = ProjectSecretAPIKeyAuthentication()
+ request = self.factory.get(
+ f"/api/projects/{team.id}/endpoints/my_endpoint/run/", HTTP_AUTHORIZATION=f"Bearer {token}"
+ )
+
+ result = auth.authenticate(request)
+ assert result is not None
+ user, _ = result
+ self.assertIsInstance(user, ProjectSecretAPIKeyUser)
+
def test_sso_authentication_backend_bypasses_two_factor(self):
"""Integration test: SSO authentication backends should bypass 2FA enforcement"""
auth = SessionAuthentication()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2788dac389d5..5b8f9e035d57 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -25689,6 +25689,7 @@ export namespace Schemas {
readonly last_used_at: string | null;
/** @nullable */
readonly last_rolled_at: string | null;
+ /** Project-wide API scopes granted to this key. Project secret API keys do not honor object-level access controls, so a scope can access resources of that type even when per-resource RBAC would hide them from an individual user. */
scopes: string[];
}
@@ -32473,6 +32474,7 @@ export namespace Schemas {
readonly last_used_at?: string | null;
/** @nullable */
readonly last_rolled_at?: string | null;
+ /** Project-wide API scopes granted to this key. Project secret API keys do not honor object-level access controls, so a scope can access resources of that type even when per-resource RBAC would hide them from an individual user. */
scopes?: string[];
}