Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(cdp): restore api token auth on hog function templates (#61920)

Raúl Negrón-Oteroa846812b772b
diff --git a/products/cdp/backend/api/hog_function_template.py b/products/cdp/backend/api/hog_function_template.py
index 5cceaa2ed50b..609886924f9b 100644
--- a/products/cdp/backend/api/hog_function_template.py
+++ b/products/cdp/backend/api/hog_function_template.py
@@ -1,11 +1,19 @@
+from functools import cached_property
+
from django.db.models import Count, QuerySet
import structlog
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema
from rest_framework import mixins, permissions, serializers, viewsets
+from rest_framework.exceptions import NotFound
from rest_framework.request import Request
+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.models.team import Team
+from posthog.models.user import User
+from posthog.permissions import APIScopePermission
+
from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
from products.cdp.backend.models.hog_functions import HogFunction
@@ -87,6 +95,31 @@ class PublicHogFunctionTemplateViewSet(
serializer_class = HogFunctionTemplateSerializer
queryset = HogFunctionTemplate.objects.all()
lookup_field = "template_id"
+ # Plain GenericViewSet doesn't inherit TeamAndOrgViewSetMixin's authenticators, so the global
+ # default (SessionAuthentication only) applies. Declare the API-token authenticators explicitly
+ # so personal API key / OAuth callers (the MCP server, public API) can reach the authenticated
+ # project-nested mount — without these, IsAuthenticated rejects every non-cookie request as 401.
+ authentication_classes = [
+ OAuthAccessTokenAuthentication,
+ PersonalAPIKeyAuthentication,
+ SessionAuthentication,
+ ]
+
+ @cached_property
+ def team(self) -> Team:
+ # APIScopePermission resolves `view.team` to enforce a token's `scoped_teams`/`scoped_organizations`
+ # and org-level key restrictions. This viewset isn't a TeamAndOrgViewSetMixin, so provide the
+ # minimal resolution from the project-nested URL kwarg ourselves.
+ project_id = self.kwargs.get("parent_lookup_project_id")
+ if project_id == "@current":
+ user = self.request.user
+ if isinstance(user, User) and user.team is not None:
+ return user.team
+ raise NotFound("Project not found.")
+ try:
+ return Team.objects.select_related("organization").get(id=project_id)
+ except (Team.DoesNotExist, ValueError, TypeError):
+ raise NotFound("Project not found.")
def get_permissions(self):
# The dedicated public catalog endpoint is intentionally anonymous. The project-nested
@@ -94,7 +127,10 @@ class PublicHogFunctionTemplateViewSet(
# ones) to anonymous callers.
if self.request.path.startswith("/api/public_hog_function_templates"):
return [permissions.AllowAny()]
- return [permissions.IsAuthenticated()]
+ # IsAuthenticated blocks anonymous callers; APIScopePermission enforces the `hog_function`
+ # scope (and team/org scoping) for personal API key / OAuth tokens. IsAuthenticated must stay
+ # first — APIScopePermission alone treats credential-less requests as session auth and allows them.
+ return [permissions.IsAuthenticated(), APIScopePermission()]
def filter_queryset(self, queryset: QuerySet) -> QuerySet:
if self.action == "list":
diff --git a/products/cdp/backend/api/test/test_hog_function_templates.py b/products/cdp/backend/api/test/test_hog_function_templates.py
index bfef53ac6bc6..3a60ccd71a4a 100644
--- a/products/cdp/backend/api/test/test_hog_function_templates.py
+++ b/products/cdp/backend/api/test/test_hog_function_templates.py
@@ -8,6 +8,8 @@ from rest_framework import status
from posthog.cdp.templates.hog_function_template import sync_template_to_db
from posthog.cdp.templates.slack.template_slack import template as template_slack
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
@@ -321,3 +323,45 @@ class TestHogFunctionTemplates(ClickhouseTestMixin, APIBaseTest, QueryMatchingTe
response = self.client.get(f"/api/projects/{self.team.id}/hog_function_templates/")
assert response.status_code == status.HTTP_200_OK, response.json()
assert "template-hidden" not in [template["id"] for template in response.json()["results"]]
+
+ def _get_with_pak(self, suffix, scopes, scoped_teams=None):
+ key_value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="Test key",
+ user=self.user,
+ secure_value=hash_key_value(key_value),
+ scopes=scopes,
+ scoped_teams=scoped_teams or [],
+ )
+ self.client.logout()
+ return self.client.get(
+ f"/api/projects/{self.team.id}{suffix}",
+ headers={"authorization": f"Bearer {key_value}"},
+ )
+
+ @parameterized.expand(
+ [
+ ("list", "/hog_function_templates/"),
+ ("retrieve", "/hog_function_templates/template-slack"),
+ ]
+ )
+ def test_project_route_authenticates_personal_api_key(self, _name, suffix):
+ # The project-nested mount requires authentication but isn't a TeamAndOrgViewSetMixin, so it
+ # must declare the API-token authenticators itself. Guard against a regression to session-only
+ # auth that would 401 the MCP server and public API.
+ response = self._get_with_pak(suffix, ["hog_function:read"])
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ def test_project_route_enforces_hog_function_scope(self):
+ # A token without the hog_function scope is rejected — scope_object is enforced, not decorative.
+ response = self._get_with_pak("/hog_function_templates/", ["feature_flag:read"])
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+
+ def test_project_route_allows_key_scoped_to_this_project(self):
+ response = self._get_with_pak("/hog_function_templates/", ["hog_function:read"], scoped_teams=[self.team.id])
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ def test_project_route_rejects_key_scoped_to_another_project(self):
+ other_team = self.create_team_with_organization(self.organization)
+ response = self._get_with_pak("/hog_function_templates/", ["hog_function:read"], scoped_teams=[other_team.id])
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()