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): wire project secret API key auth into EndpointViewSet (#56190)

Jovan Sakovic2fbfdf7afde4
diff --git a/posthog/clickhouse/client/execute.py b/posthog/clickhouse/client/execute.py
index 9f2479b25b00..4cccc2d3badc 100644
--- a/posthog/clickhouse/client/execute.py
+++ b/posthog/clickhouse/client/execute.py
@@ -28,7 +28,6 @@ from posthog.clickhouse.client.connection import (
from posthog.clickhouse.client.escape import substitute_params
from posthog.clickhouse.client.tracing import trace_clickhouse_query_decorator
from posthog.clickhouse.query_tagging import (
- AccessMethod,
Feature,
Product,
QueryTags,
@@ -36,6 +35,7 @@ from posthog.clickhouse.query_tagging import (
get_caller_source,
get_query_tag_value,
get_query_tags,
+ is_api_key_access_method,
)
from posthog.errors import clickhouse_error_type, wrap_clickhouse_query_error
from posthog.settings import CLICKHOUSE_PER_TEAM_QUERY_SETTINGS, DEBUG, TEST
@@ -314,18 +314,21 @@ def sync_execute(
except ModuleNotFoundError: # when we run plugin server tests it tries to run above, ignore
pass
tags = get_query_tags()
- is_personal_api_key = tags.access_method == AccessMethod.PERSONAL_API_KEY
+ # Any programmatic key auth — personal API key, project secret API key, or legacy team secret
+ # token — routes to the offline cluster as the API ClickHouse user. User-facing session/OAuth
+ # traffic stays on the online cluster. See is_api_key_access_method for the exact set.
+ is_api_key_auth = is_api_key_access_method(tags.access_method)
# When someone uses an API key, always put their query to the offline cluster
# Execute all celery tasks not directly set to be online on the offline cluster
- if workload == Workload.DEFAULT and (is_personal_api_key or tags.kind == "celery"):
+ if workload == Workload.DEFAULT and (is_api_key_auth or tags.kind == "celery"):
workload = Workload.OFFLINE
# Make sure we always have process_query_task on the online cluster
tags_id: str = tags.id or ""
if tags_id == "posthog.tasks.tasks.process_query_task":
workload = Workload.ONLINE
- ch_user = ClickHouseUser.API if is_personal_api_key else ClickHouseUser.APP
+ ch_user = ClickHouseUser.API if is_api_key_auth else ClickHouseUser.APP
if tags.workload == Workload.ENDPOINTS:
workload = Workload.ENDPOINTS
@@ -355,7 +358,7 @@ def sync_execute(
tags.query_settings = core_settings
query_type = tags.query_type or "Other"
if ch_user == ClickHouseUser.DEFAULT:
- if is_personal_api_key:
+ if is_api_key_auth:
ch_user = ClickHouseUser.API
elif tags.kind == "request" and "api/" in tags_id and "capture" not in tags_id:
# process requests made to API from the PH app
diff --git a/posthog/clickhouse/test/test_query_tagging.py b/posthog/clickhouse/test/test_query_tagging.py
index 418cc0a40467..c4cab4eb767b 100644
--- a/posthog/clickhouse/test/test_query_tagging.py
+++ b/posthog/clickhouse/test/test_query_tagging.py
@@ -14,6 +14,7 @@ from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.query_tagging import (
_PROJECT_ROOT_PREFIX,
_SOURCE_SKIP_PREFIXES,
+ AccessMethod,
Feature,
HogQLFeatures,
Product,
@@ -25,6 +26,7 @@ from posthog.clickhouse.query_tagging import (
get_caller_source,
get_query_tag_value,
get_query_tags,
+ is_api_key_access_method,
reset_query_tags,
tag_contains_user_hogql,
tag_queries,
@@ -693,3 +695,22 @@ class TestAddFallbackQueryTags(BaseTest):
)
add_fallback_query_tags(tags)
assert tags.product == Product.MCP
+
+
+ "access_method,expected",
+ [
+ # Programmatic key auth routes ClickHouse queries to the offline cluster as the API user
+ # (see sync_execute); user-facing auth stays online.
+ (AccessMethod.PERSONAL_API_KEY, True),
+ (AccessMethod.PROJECT_SECRET_API_KEY, True),
+ (AccessMethod.TEAM_SECRET_TOKEN, True),
+ (AccessMethod.OAUTH, False),
+ (AccessMethod.SHARING_TOKEN, False),
+ (AccessMethod.ID_JAG, False),
+ (None, False),
+ ("", False),
+ ],
+)
+def test_is_api_key_access_method(access_method, expected):
+ assert is_api_key_access_method(access_method) is expected
diff --git a/posthog/event_usage.py b/posthog/event_usage.py
index a1359509d50f..a64c69de580f 100644
--- a/posthog/event_usage.py
+++ b/posthog/event_usage.py
@@ -18,6 +18,7 @@ from posthog.models import Organization, User
from posthog.models.activity_logging.model_activity import is_impersonated_session
from posthog.models.team import Team
from posthog.settings import SITE_URL
+from posthog.synthetic_user import SyntheticUser
from posthog.utils import get_instance_realm
if TYPE_CHECKING:
@@ -389,7 +390,7 @@ _tracer = trace.get_tracer(__name__)
def report_user_action(
- user: User | AnonymousUser,
+ user: User | AnonymousUser | SyntheticUser,
event: str,
properties: Optional[dict] = None,
*,
@@ -399,9 +400,6 @@ def report_user_action(
analytics_props: Optional[AnalyticsProps] = None,
send_feature_flags: bool = False,
):
- # isinstance works through Django's SimpleLazyObject because it proxies __class__
- if not isinstance(user, User) or not user.distinct_id:
- return
if request is not None and analytics_props is not None:
raise ValueError("Pass either request or analytics_props, not both")
if properties is None:
@@ -410,6 +408,22 @@ def report_user_action(
properties = {**get_request_analytics_properties(request), **properties}
if analytics_props is not None:
properties = {**analytics_props, **properties}
+
+ # Synthetic principals (e.g. project secret API keys) have no User row but still carry a
+ # distinct_id, so service-authenticated actions are captured instead of silently dropped.
+ if isinstance(user, SyntheticUser):
+ synthetic_team = team or user.team
+ posthoganalytics.capture(
+ distinct_id=user.distinct_id,
+ event=event,
+ properties=properties,
+ groups=groups(organization or synthetic_team.organization, synthetic_team),
+ )
+ return
+
+ # isinstance works through Django's SimpleLazyObject because it proxies __class__
+ if not isinstance(user, User) or not user.distinct_id:
+ return
if user.email:
properties["$set_once"] = {"email": user.email}
with _tracer.start_as_current_span("report_user_action"):
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 2deece70b9a1..fcf5ac19a4bf 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -92,7 +92,7 @@ from posthog.clickhouse.client.limit import (
get_materialized_endpoints_rate_limiter,
get_org_app_concurrency_limit,
)
-from posthog.clickhouse.query_tagging import get_query_tag_value, tag_queries
+from posthog.clickhouse.query_tagging import get_query_tag_value, is_api_key_access_method, tag_queries
from posthog.errors import QueryErrorCategory, classify_query_error, clickhouse_error_type
from posthog.event_usage import AnalyticsProps, groups, report_user_or_team_action
from posthog.exceptions_capture import capture_exception
@@ -1401,7 +1401,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
"""
concurrency_limit = self.get_api_queries_concurrency_limit()
is_materialized_endpoint = get_query_tag_value("workload") == Workload.ENDPOINTS
- is_api_key_access = get_query_tag_value("access_method") == "personal_api_key"
+ is_api_key_access = is_api_key_access_method(get_query_tag_value("access_method"))
if self.is_query_service:
tag_queries(chargeable=1)
diff --git a/posthog/models/test/test_project_secret_api_key.py b/posthog/models/test/test_project_secret_api_key.py
new file mode 100644
index 000000000000..7bb86b17d442
--- /dev/null
+++ b/posthog/models/test/test_project_secret_api_key.py
@@ -0,0 +1,37 @@
+from posthog.test.base import BaseTest
+
+from posthog.models.project_secret_api_key import ProjectSecretAPIKey, find_project_secret_api_key
+from posthog.models.utils import hash_key_value
+
+
+class TestFindProjectSecretAPIKey(BaseTest):
+ def test_match(self):
+ token = "phs_" + "m" * 35
+ psak = ProjectSecretAPIKey.objects.create(
+ team=self.team,
+ label="lookup",
+ secure_value=hash_key_value(token),
+ scopes=["endpoint:read"],
+ )
+
+ found = find_project_secret_api_key(token)
+ assert found is not None
+ self.assertEqual(found.pk, psak.pk)
+
+ def test_no_match(self):
+ self.assertIsNone(find_project_secret_api_key("phs_" + "q" * 35))
+
+ def test_hash_isolation(self):
+ token_a = "phs_" + "a" * 35
+ token_b = "phs_" + "b" * 35
+ psak_a = ProjectSecretAPIKey.objects.create(
+ team=self.team,
+ label="a",
+ secure_value=hash_key_value(token_a),
+ )
+
+ found = find_project_secret_api_key(token_a)
+ assert found is not None
+ self.assertEqual(found.pk, psak_a.pk)
+
+ self.assertIsNone(find_project_secret_api_key(token_b))
diff --git a/products/endpoints/backend/api.py b/products/endpoints/backend/api.py
index 68c3ba7915ab..f8d6bd1c795c 100644
--- a/products/endpoints/backend/api.py
+++ b/products/endpoints/backend/api.py
@@ -61,9 +61,16 @@ from posthog.api.services.query import process_query_model
from posthog.api.shared import UserBasicSerializer
from posthog.api.tagged_item import TaggedItemViewSetMixin, cleanup_orphan_tags, set_tags_on_object
from posthog.api.utils import action
+from posthog.auth import ProjectSecretAPIKeyAuthentication
from posthog.clickhouse.client.connection import Workload
from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
-from posthog.clickhouse.query_tagging import Feature, Product, get_query_tag_value, tag_queries
+from posthog.clickhouse.query_tagging import (
+ Feature,
+ Product,
+ get_query_tag_value,
+ is_api_key_access_method,
+ tag_queries,
+)
from posthog.ducklake.common import get_duckgres_server_for_organization
from posthog.errors import ExposedCHQueryError
from posthog.event_usage import get_request_analytics_properties, report_user_action
@@ -78,10 +85,15 @@ from posthog.models.activity_logging.activity_log import (
changes_between,
log_activity,
)
-from posthog.permissions import APIScopePermission, TeamMemberAccessPermission
+from posthog.permissions import (
+ APIScopePermission,
+ TeamMemberAccessPermission,
+ is_authenticated_via_project_secret_api_key,
+)
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from posthog.rbac.user_access_control import access_level_satisfied_for_resource
from posthog.schema_migrations.upgrade import upgrade
+from posthog.synthetic_user import SyntheticUser
from posthog.types import InsightQueryNode
from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
@@ -121,6 +133,8 @@ from products.endpoints.backend.models import Endpoint, EndpointVersion
from products.endpoints.backend.openapi import generate_openapi_spec
from products.endpoints.backend.rate_limit import (
EndpointBurstThrottle,
+ EndpointProjectSecretApiKeyTeamBurstThrottle,
+ EndpointProjectSecretApiKeyTeamSustainedThrottle,
EndpointSustainedThrottle,
clear_endpoint_materialization_cache,
)
@@ -415,6 +429,8 @@ class EndpointViewSet(
LogEntryMixin,
viewsets.ModelViewSet,
):
+ authentication_classes = [ProjectSecretAPIKeyAuthentication]
+ psak_allowed_actions = ["run"]
# NOTE: Do we need to override the scopes for the "create"
scope_object = "endpoint"
# Read endpoint execution logs from the `log_entries` table keyed by this source.
@@ -449,7 +465,12 @@ class EndpointViewSet(
return serializers.Serializer # We use Pydantic models instead; this fallback satisfies drf-spectacular
def get_throttles(self):
- return [EndpointBurstThrottle(), EndpointSustainedThrottle()]
+ return [
+ EndpointBurstThrottle(),
+ EndpointSustainedThrottle(),
+ EndpointProjectSecretApiKeyTeamBurstThrottle(),
+ EndpointProjectSecretApiKeyTeamSustainedThrottle(),
+ ]
def dangerously_get_permissions(self):
# `run` is the public-facing execution API. It still requires authentication, the
@@ -479,6 +500,11 @@ class EndpointViewSet(
defaults so a restrictive project default doesn't break the public execution API. Creators
and org admins always pass (specific_access_level_for_object returns the highest level).
"""
+ # PSAK scopes are project-wide within their resource type and deliberately ignore
+ # object-level access controls — the key's team binding and `endpoint:read` scope are
+ # the whole authorization story (see posthog/scopes.py).
+ if is_authenticated_via_project_secret_api_key(self.request):
+ return
specific_level = self.user_access_control.specific_access_level_for_object(endpoint)
if specific_level is not None and not access_level_satisfied_for_resource("endpoint", specific_level, "viewer"):
raise PermissionDenied("You do not have access to this endpoint.")
@@ -1610,7 +1636,7 @@ class EndpointViewSet(
execution_mode=execution_mode,
query_id=client_query_id,
user=cast(User, request.user),
- is_query_service=(get_query_tag_value("access_method") == "personal_api_key"),
+ is_query_service=is_api_key_access_method(get_query_tag_value("access_method")),
cache_age_seconds=cache_age_seconds,
analytics_props=get_request_analytics_properties(request),
)
@@ -2099,24 +2125,24 @@ class EndpointViewSet(
return DashboardFilter(date_from=date_from, date_to=date_to, properties=properties)
def _should_use_ducklake(self, endpoint: Endpoint, version: EndpointVersion | None) -> bool:
- if version is None:
- return False
- if version.query.get("kind") != "HogQLQuery":
+ if version is None or version.query.get("kind") != "HogQLQuery":
return False
- user_email = getattr(self.request.user, "email", "") if self.request else ""
ff_result = posthoganalytics.feature_enabled(
"endpoints-ducklake-execution",
- user_email,
- person_properties={"email": str(user_email)},
+ str(self.team.uuid),
+ groups={
+ "organization": str(self.team.organization_id),
+ "project": str(self.team.id),
+ },
+ group_properties={
+ "organization": {"id": str(self.team.organization_id)},
+ "project": {"id": str(self.team.id)},
+ },
only_evaluate_locally=True,
send_feature_flag_events=False,
)
- logger.info(
- "Ducklake FF evaluation",
- endpoint_name=endpoint.name,
- ff_result=ff_result,
- )
+ logger.info("Ducklake FF evaluation", endpoint_name=endpoint.name, ff_result=ff_result)
if not ff_result:
return False
@@ -2335,9 +2361,8 @@ class EndpointViewSet(
try:
data = self._parse_run_request(request)
- # Track endpoint execution for deprecation monitoring
report_user_action(
- user=cast(User, request.user),
+ user=cast("User | SyntheticUser", request.user),
event="endpoint executed",
properties={
"endpoint_id": str(endpoint.id),
@@ -2347,6 +2372,9 @@ class EndpointViewSet(
"has_limit": data.limit is not None,
"has_offset": data.offset is not None,
"refresh_mode": data.refresh.value if data.refresh else None,
+ "auth_method": "project_secret_api_key"
+ if is_authenticated_via_project_secret_api_key(request)
+ else "user",
},
team=self.team,
request=request,
@@ -2529,7 +2557,7 @@ class EndpointViewSet(
),
)
- if get_query_tag_value("access_method") == "personal_api_key":
+ if is_api_key_access_method(get_query_tag_value("access_method")):
now = timezone.now()
throttle = timedelta(minutes=30)
if endpoint.last_executed_at is None or (now - endpoint.last_executed_at > throttle):
diff --git a/products/endpoints/backend/rate_limit.py b/products/endpoints/backend/rate_limit.py
index 1d23ec1a0662..d48314b98c92 100644
--- a/products/endpoints/backend/rate_limit.py
+++ b/products/endpoints/backend/rate_limit.py
@@ -1,6 +1,13 @@
from django.core.cache import cache
-from posthog.rate_limit import APIQueriesBurstThrottle, APIQueriesSustainedThrottle
+from rest_framework.throttling import SimpleRateThrottle
+
+from posthog.rate_limit import (
+ APIQueriesBurstThrottle,
+ APIQueriesSustainedThrottle,
+ PersonalOrProjectSecretApiKeyRateThrottle,
+ ProjectSecretApiKeyTeamRateThrottle,
+)
from products.endpoints.backend.metrics import ENDPOINT_RATE_LIMITED_TOTAL
@@ -91,17 +98,21 @@ def _is_materialized_endpoint_request(request, view) -> bool:
return cached_status
-class EndpointBurstThrottle(APIQueriesBurstThrottle):
- """
- Adaptive burst throttle for endpoints.
- Uses higher rate limit for materialized endpoints.
- Non-materialized endpoints share the api_queries_burst bucket.
+class _MaterializedRateMixin(SimpleRateThrottle):
+ """Swaps in the higher materialized-endpoint rate and records 429s, on top of any base throttle.
+
+ Mix in before a SimpleRateThrottle subclass — `allow_request` adjusts the rate/scope for
+ materialized endpoints, then defers to the base throttle's own gating (which sits between
+ this mixin and SimpleRateThrottle in the MRO).
"""
+ materialized_rate: str
+ materialized_scope: str
+
def allow_request(self, request, view):
if _is_materialized_endpoint_request(request, view):
- self.rate = "1200/minute"
- self.scope = "materialized_endpoint_burst"
+ self.rate = self.materialized_rate
+ self.scope = self.materialized_scope
self.num_requests, self.duration = self.parse_rate(self.rate)
allowed = super().allow_request(request, view)
@@ -113,23 +124,45 @@ class EndpointBurstThrottle(APIQueriesBurstThrottle):
return allowed
-class EndpointSustainedThrottle(APIQueriesSustainedThrottle):
+class EndpointBurstThrottle(_MaterializedRateMixin, PersonalOrProjectSecretApiKeyRateThrottle, APIQueriesBurstThrottle):
+ """
+ Adaptive burst throttle for endpoints, keyed per credential (personal API key or PSAK).
+ Uses higher rate limit for materialized endpoints.
+ Non-materialized endpoints share the api_queries_burst bucket.
+ """
+
+ materialized_rate = "1200/minute"
+ materialized_scope = "materialized_endpoint_burst"
+
+
+class EndpointSustainedThrottle(
+ _MaterializedRateMixin, PersonalOrProjectSecretApiKeyRateThrottle, APIQueriesSustainedThrottle
+):
"""
- Adaptive sustained throttle for endpoints.
+ Adaptive sustained throttle for endpoints, keyed per credential (personal API key or PSAK).
Uses higher rate limit for materialized endpoints.
Non-materialized endpoints share the api_queries_sustained bucket.
"""
- def allow_request(self, request, view):
- if _is_materialized_endpoint_request(request, view):
- self.rate = "12000/hour"
- self.scope = "materialized_endpoint_sustained"
- self.num_requests, self.duration = self.parse_rate(self.rate)
+ materialized_rate = "12000/hour"
+ materialized_scope = "materialized_endpoint_sustained"
- allowed = super().allow_request(request, view)
- if not allowed:
- try:
- ENDPOINT_RATE_LIMITED_TOTAL.labels(scope=self.scope).inc()
- except Exception:
- pass
- return allowed
+
+class EndpointProjectSecretApiKeyTeamBurstThrottle(_MaterializedRateMixin, ProjectSecretApiKeyTeamRateThrottle):
+ """Per-team aggregate burst budget across all of a project's PSAKs — same size as the per-key
+ budget, so minting extra keys never multiplies a project's total burst capacity."""
+
+ # Own scope (not api_queries_burst) so 429 metrics and cache keys name the bucket that tripped.
+ scope = "endpoint_psak_team_burst"
+ rate = APIQueriesBurstThrottle.rate
+ materialized_rate = EndpointBurstThrottle.materialized_rate
+ materialized_scope = "materialized_endpoint_psak_team_burst"
+
+
+class EndpointProjectSecretApiKeyTeamSustainedThrottle(_MaterializedRateMixin, ProjectSecretApiKeyTeamRateThrottle):
+ """Per-team aggregate sustained budget across all of a project's PSAKs."""
+
+ scope = "endpoint_psak_team_sustained"
+ rate = APIQueriesSustainedThrottle.rate
+ materialized_rate = EndpointSustainedThrottle.materialized_rate
+ materialized_scope = "materialized_endpoint_psak_team_sustained"
diff --git a/products/endpoints/backend/tests/test_endpoint_psak_auth.py b/products/endpoints/backend/tests/test_endpoint_psak_auth.py
new file mode 100644
index 000000000000..6c44ce2c853e
--- /dev/null
+++ b/products/endpoints/backend/tests/test_endpoint_psak_auth.py
@@ -0,0 +1,380 @@
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from unittest.mock import patch
+
+from django.core.cache import cache
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.hogql.database.database import _compute_system_table_access_decision
+
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.project_secret_api_key import ProjectSecretAPIKey
+from posthog.models.team import Team
+from posthog.models.utils import hash_key_value
+from posthog.rbac.user_access_control import UserAccessControl
+
+from products.endpoints.backend.tests.conftest import create_endpoint_with_version
+
+SAMPLE_QUERY = {"kind": "HogQLQuery", "query": "SELECT 1"}
+_UNSET = object()
+
+
+def _ff_returns_true_for_hogql_access_control(flag_key, *args, **kwargs):
+ return True if flag_key == "hogql-access-control" else False
+
+
+def _make_psak(team, label="psak", scopes=_UNSET):
+ # Token must match _SECRET_API_KEY_RE = r"^phs_[a-zA-Z0-9]+$", so only alphanumerics after phs_.
+ suffix = "".join(c for c in label if c.isalnum())
+ token = "phs_" + ("a" * 35) + suffix
+ psak = ProjectSecretAPIKey.objects.create(
+ team=team,
+ label=label,
+ mask_value=f"phs_...{suffix[:4]}",
+ secure_value=hash_key_value(token),
+ scopes=["endpoint:read"] if scopes is _UNSET else scopes,
+ )
+ return token, psak
+
+
+class TestEndpointViewSetPSAKAuth(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.endpoint = create_endpoint_with_version(
+ name="my_endpoint",
+ team=self.team,
+ query=SAMPLE_QUERY,
+ created_by=self.user,
+ )
+ # Log out the test client so only the PSAK header authenticates requests
+ self.client.logout()
+
+ def _auth_headers(self, token):
+ return {"HTTP_AUTHORIZATION": f"Bearer {token}"}
+
+ def test_psak_can_run_endpoint(self):
+ token, _ = _make_psak(self.team, label="run-key")
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/endpoints/my_endpoint/run/",
+ data={},
+ content_type="application/json",
+ **self._auth_headers(token),
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+
+ def test_psak_can_run_endpoint_via_get(self):
+ # `run` accepts both GET and POST; both resolve to the same action and must pass the
+ # psak_allowed_actions gate.
+ token, _ = _make_psak(self.team, label="get-key")
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/endpoints/my_endpoint/run/",
+ **self._auth_headers(token),
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+
+ def test_psak_run_on_inactive_endpoint_returns_404(self):
+ self.endpoint.is_active = False
+ self.endpoint.save()
+ token, _ = _make_psak(self.team, label="inactive-key")
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/endpoints/my_endpoint/run/",
+ data={},
+ content_type="application/json",
+ **self._auth_headers(token),
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND, response.content)
+
+ def test_psak_run_skips_object_level_access_check(self):
+ # PSAK scopes are project-wide by design: object-level access controls are only defined
+ # for members/roles, which a synthetic principal has neither of, so run() must not
+ # consult UserAccessControl at all for PSAK requests.
+ token, _ = _make_psak(self.team, label="acl-skip-key")
+
+ with patch.object(UserAccessControl, "specific_access_level_for_object") as acl_spy:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/endpoints/my_endpoint/run/",
+ data={},
+ content_type="application/json",
+ **self._auth_headers(token),
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ acl_spy.assert_not_called()
+
+ def test_psak_run_updates_last_executed_at(self):
+ # Freshness tracking gates on "any API-key access method", not just personal API keys —
+ # a PSAK-only consumer must not look stale to the materialization-cleanup task.
+ token, _ = _make_psak(self.team, label="freshness-key")
+ self.assertIsNone(self.endpoint.last_executed_at)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/endpoints/my_endpoint/run/",
+ data={},
+ content_type="application/json",
+ **self._auth_headers(token),
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.endpoint.refresh_from_db()
+ self.assertIsNotNone(self.endpoint.last_executed_at)
+ version = self.endpoint.get_version()
+ assert version is not None
+ self.assertIsNotNone(version.last_executed_at)
+
+ def test_psak_run_is_captured_with_synthetic_distinct_id(self):
+ # report_user_action handles synthetic principals by capturing with their distinct_id —
+ # otherwise key-driven traffic would be invisible to deprecation monitoring.
+ token, psak = _make_psak(self.team, label="telemetry-key")
+
+ with patch("posthog.event_usage.posthoganalytics.capture") as capture_mock:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/endpoints/my_endpoint/run/",
+ data={},
+ content_type="application/json",
+ **self._auth_headers(token),
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ executed_calls = [c for c in capture_mock.call_args_list if c.kwargs.get("event") == "endpoint executed"]
+ self.assertEqual(len(executed_calls), 1)
+ kwargs = executed_calls[0].kwargs
+ self.assertEqual(kwargs["distinct_id"], f"psak-{self.team.id}-{psak.id}")
+ self.assertEqual(kwargs["properties"]["auth_method"], "project_secret_api_key")
+ self.assertEqual(kwargs["properties"]["endpoint_name"], "my_endpoint")
+ self.assertEqual(kwargs["groups"]["project"], str(self.team.uuid))
+ self.assertNotIn("$set_once", kwargs["properties"])
+
+ def test_session_run_is_reported_as_user_action(self):
+ # The user-auth path keeps the same event shape, captured under the real user's distinct_id.
+ self.client.force_login(self.user)
+
+ with patch("posthog.event_usage.posthoganalytics.capture") as capture_mock:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/endpoints/my_endpoint/run/",
+ data={},
+ content_type="application/json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ executed_calls = [c for c in capture_mock.call_args_list if c.kwargs.get("event") == "endpoint executed"]
+ self.assertEqual(len(executed_calls), 1)
+ kwargs = executed_calls[0].kwargs
+ self.assertEqual(kwargs["distinct_id"], self.user.distinct_id)
+ self.assertEqual(kwargs["properties"]["auth_method"], "user")
+ self.assertEqual(kwargs["properties"]["endpoint_name"], "my_endpoint")
+
+ def test_psak_in_body_is_not_accepted(self):
+ token, _ = _make_psak(self.team, label="body-key")
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/endpoints/my_endpoint/run/",
+ data={"secret_api_key": token},
+ content_type="application/json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED, response.content)
+
+ def test_psak_can_run_endpoint_with_hogql_access_control_on(self):
+ # Without the FF mock, the test path skips the access-control branch
+ # in posthog/hogql/database/database.py and never exercises the
+ # synthetic-user code path.
+ token, _ = _make_psak(self.team, label="run-with-rbac")
+
+ captured: dict = {}
+
+ def spy(team, user):
+ result = _compute_system_table_access_decision(team, user)
+ captured.setdefault("results", []).append(result)
+ return result
+
+ with (
+ patch("posthoganalytics.feature_enabled", side_effect=_ff_returns_true_for_hogql_access_control),
+ patch("posthog.hogql.database.database._compute_system_table_access_decision", side_effect=spy),
+ ):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/endpoints/my_endpoint/run/",
+ data={},
+ content_type="application/json",
+ **self._auth_headers(token),
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.assertTrue(captured.get("results"), "access-control decision was never exercised")
+ for user_access_control, denied in captured["results"]:
+ self.assertIsNone(user_access_control)
+ self.assertNotIn("data_modeling_endpoints", denied)
+ self.assertNotIn("data_modeling_endpoint_versions", denied)
+
+ @parameterized.expand(
+ [
+ # PSAK must only authorize the `run` action — every other action returns 403.
+ ("list", "GET", ""),
+ ("retrieve", "GET", "my_endpoint/"),
+ ("update", "PUT", "my_endpoint/"),
+ ("partial_update", "PATCH", "my_endpoint/"),
+ ("destroy", "DELETE", "my_endpoint/"),
+ ("openapi_spec", "GET", "my_endpoint/openapi.json/"),
+ ("materialization_status", "GET", "my_endpoint/materialization_status/"),
+ ("materialization_preview", "POST", "my_endpoint/materialization_preview/"),
+ ("versions", "GET", "my_endpoint/versions/"),
+ ("last_execution_times", "POST", "last_execution_times/"),
+ ]
+ )
+ def test_psak_blocked_on_non_run_actions(self, _name, method, path_suffix):
+ token, _ = _make_psak(self.team, label=f"non-run-{_name}")
+
+ response = self.client.generic(
+ method,
+ f"/api/projects/{self.team.id}/endpoints/{path_suffix}",
+ **self._auth_headers(token),
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)
+ self.assertIn("does not support project secret API key", response.json().get("detail", ""))
+
+ def test_psak_blocked_on_create(self):
+ token, _ = _make_psak(self.team, label="create-key")
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/endpoints/",
+ data={"name": "new_endpoint", "query": SAMPLE_QUERY},
+ content_type="application/json",
+ **self._auth_headers(token),
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertIn("does not support project secret API key", response.json().get("detail", ""))
+
+ @parameterized.expand(
+ [
+ ("empty_list", []),
+ ("null", None),
+ ]
+ )
+ def test_psak_without_endpoint_scope_returns_403(self, _name, scopes):
+ token, _ = _make_psak(self.team, label=f"no-scope-{_name}", scopes=scopes)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/endpoints/my_endpoint/run/",
+ data={},
+ content_type="application/json",
+ **self._auth_headers(token),
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertIn("missing required scope 'endpoint:read'", response.json().get("detail", ""))
+
+ def test_unknown_psak_returns_401(self):
+ # Valid-looking but not-in-DB token
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/endpoints/my_endpoint/run/",
+ data={},
+ content_type="application/json",
+ **self._auth_headers("phs_" + "z" * 35),
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+
+ def test_psak_team_mismatch_returns_403(self):
+ # PSAK belongs to team A; request targets team B.
+ other_org = Organization.objects.create(name="Other Org")
+ other_team = Team.objects.create(organization=other_org, name="Other Team")
+
+ token, _ = _make_psak(self.team, label="team-mismatch-key")
+
+ response = self.client.post(
+ f"/api/projects/{other_team.id}/endpoints/my_endpoint/run/",
+ data={},
+ content_type="application/json",
+ **self._auth_headers(token),
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertIn("does not have access to the requested project", response.json().get("detail", ""))
+
+ def test_psak_does_not_authenticate_legacy_team_token_surfaces(self):
+ # remote_config is the remaining Django surface for the legacy per-team
+ # Team.secret_api_token (local_evaluation now lives in the Rust flags service).
+ # A PSAK is also phs_-prefixed but must not be accepted there.
+ token, _ = _make_psak(self.team, label="remote-config-key")
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/feature_flags/some_flag/remote_config/",
+ **self._auth_headers(token),
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED, response.content)
+
+ def test_session_auth_still_works_on_endpoint_viewset(self):
+ # Regression: wiring PSAK into authentication_classes must not break session auth.
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ self.client.force_login(self.user)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/endpoints/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+
+@patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)
+@patch("products.endpoints.backend.rate_limit.EndpointBurstThrottle.rate", new="2/minute")
+class TestEndpointPSAKRateLimit(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.endpoint = create_endpoint_with_version(
+ name="rl_endpoint",
+ team=self.team,
+ query=SAMPLE_QUERY,
+ created_by=self.user,
+ )
+ self.client.logout()
+ cache.clear()
+
+ def tearDown(self):
+ cache.clear()
+ super().tearDown()
+
+ def _run(self, token: str | None = None):
+ url = f"/api/projects/{self.team.id}/endpoints/rl_endpoint/run/"
+ if token is None:
+ return self.client.post(url, data={}, content_type="application/json")
+ return self.client.post(url, data={}, content_type="application/json", HTTP_AUTHORIZATION=f"Bearer {token}")
+
+ def test_psak_requests_are_throttled(self, *_args):
+ token, _psak = _make_psak(self.team, label="rl-key")
+
+ for _ in range(2):
+ self.assertEqual(self._run(token).status_code, status.HTTP_200_OK)
+
+ self.assertEqual(self._run(token).status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+
+ def test_distinct_psak_keys_get_independent_buckets(self, *_args):
+ token_a, _a = _make_psak(self.team, label="key-a")
+ token_b, _b = _make_psak(self.team, label="key-b")
+
+ for _ in range(2):
+ self.assertEqual(self._run(token_a).status_code, status.HTTP_200_OK)
+ self.assertEqual(self._run(token_a).status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+ self.assertEqual(self._run(token_b).status_code, status.HTTP_200_OK)
+
+ @patch("products.endpoints.backend.rate_limit.EndpointProjectSecretApiKeyTeamBurstThrottle.rate", new="3/minute")
+ def test_distinct_psak_keys_share_project_bucket(self, *_args):
+ token_a, _a = _make_psak(self.team, label="team-key-a")
+ token_b, _b = _make_psak(self.team, label="team-key-b")
+
+ self.assertEqual(self._run(token_a).status_code, status.HTTP_200_OK)
+ self.assertEqual(self._run(token_a).status_code, status.HTTP_200_OK)
+ self.assertEqual(self._run(token_b).status_code, status.HTTP_200_OK)
+ self.assertEqual(self._run(token_b).status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+
+ def test_session_user_is_not_throttled(self, *_args):
+ self.client.force_login(self.user)
+
+ for _ in range(4):
+ self.assertEqual(self._run().status_code, status.HTTP_200_OK)