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(api): improve project secret api key scope validation (#105467)

Tom Piccirello4b8497d20bb4
diff --git a/posthog/api/project_secret_api_key.py b/posthog/api/project_secret_api_key.py
index 65c4abba3672..ff765de1b3b5 100644
--- a/posthog/api/project_secret_api_key.py
+++ b/posthog/api/project_secret_api_key.py
@@ -1,3 +1,4 @@
+from collections.abc import Iterable
from typing import cast
from django.db import IntegrityError
@@ -6,7 +7,8 @@ from django.utils import timezone
import posthoganalytics
from rest_framework import response, serializers, status, viewsets
-from rest_framework.exceptions import ValidationError
+from rest_framework.exceptions import PermissionDenied, ValidationError
+from rest_framework.request import Request
from posthog.api.documentation import extend_schema
from posthog.api.routing import TeamAndOrgViewSetMixin
@@ -16,18 +18,37 @@ from posthog.auth import PersonalAPIKeyAuthentication, SessionAuthentication
from posthog.models import User
from posthog.models.project_secret_api_key import ProjectSecretAPIKey
from posthog.models.utils import generate_random_token_secret, hash_key_value, mask_key_value
-from posthog.permissions import TeamMemberStrictManagementPermission, TimeSensitiveActionPermission
+from posthog.permissions import (
+ TeamMemberStrictManagementPermission,
+ TimeSensitiveActionPermission,
+ get_authenticator_scopes,
+)
from posthog.scopes import (
API_SCOPE_ACTIONS,
API_SCOPE_OBJECTS,
INTERNAL_API_SCOPE_OBJECTS,
PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION,
+ scopes_not_covered,
)
from posthog.tasks.email import send_project_secret_api_key_exposed
MAX_PROJECT_SECRET_API_KEYS_PER_TEAM = 50
+def _enforce_caller_holds_scopes(request: Request, scopes: Iterable[str]) -> None:
+ """A project secret API key outlives the credential that issued it, so a scoped caller must not
+ issue one with scopes it lacks. Session auth and `*` keys carry the user's full authority."""
+ caller_scopes = get_authenticator_scopes(getattr(request, "successful_authenticator", None))
+ if caller_scopes is None or "*" in caller_scopes:
+ return
+ missing = sorted(scopes_not_covered(caller_scopes, scopes))
+ if missing:
+ raise PermissionDenied(
+ "Your API key or OAuth token can only issue a project secret API key with scopes it has. "
+ f"Use a key or token that has these scopes: {', '.join(missing)}."
+ )
+
+
class ProjectSecretAPIKeySerializer(serializers.ModelSerializer):
value = serializers.SerializerMethodField(method_name="get_key_value", read_only=True)
scopes = serializers.ListField(
@@ -96,6 +117,10 @@ class ProjectSecretAPIKeySerializer(serializers.ModelSerializer):
raise serializers.ValidationError(
f"Scope '{scope}' can not be assigned to a project secret API key. Allowed scopes: {allowed_scopes}"
)
+
+ # An update may keep or remove a scope the caller lacks, because only an added scope widens the key.
+ existing = set(self.instance.scopes or []) if self.instance is not None else set()
+ _enforce_caller_holds_scopes(self.context["request"], [scope for scope in scopes if scope not in existing])
return scopes
def _llm_gateway_grantable(self) -> bool:
@@ -199,6 +224,7 @@ class ProjectSecretAPIKeyViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
@action(methods=["POST"], detail=True, url_path="roll")
def roll(self, request, *args, **kwargs):
instance = self.get_object()
+ _enforce_caller_holds_scopes(request, instance.scopes or [])
serializer = cast(ProjectSecretAPIKeySerializer, self.get_serializer(instance))
serializer.roll(instance)
return response.Response(serializer.data, status=status.HTTP_200_OK)
diff --git a/posthog/api/test/test_project_secret_api_keys.py b/posthog/api/test/test_project_secret_api_keys.py
index 815b68ec0c84..61e0c24f51b7 100644
--- a/posthog/api/test/test_project_secret_api_keys.py
+++ b/posthog/api/test/test_project_secret_api_keys.py
@@ -443,15 +443,7 @@ class TestProjectSecretAPIKeysViaPersonalAPIKey(APIBaseTest):
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
+ self.token = self.create_personal_api_key_with_scopes(["project:write", "project:read", "endpoint:read"])
def _auth(self):
return {"HTTP_AUTHORIZATION": f"Bearer {self.token}"}
@@ -555,3 +547,111 @@ class TestProjectSecretAPIKeysViaPersonalAPIKey(APIBaseTest):
)
assert response.status_code == 200, response.content
assert ProjectSecretAPIKey.objects.get(id=key_id).label == "via-put"
+
+ @parameterized.expand(
+ [
+ ("lacks_scope", ["project:write"], ["endpoint:read"], ["endpoint:read"]),
+ (
+ "lacks_one_of_several",
+ ["project:write", "endpoint:read"],
+ ["endpoint:read", "account:read"],
+ ["account:read"],
+ ),
+ ("read_does_not_cover_write", ["project:write", "loop:read"], ["loop:write"], ["loop:write"]),
+ (
+ "lacks_several_listed_sorted",
+ ["project:write"],
+ ["loop:write", "account:read"],
+ ["account:read", "loop:write"],
+ ),
+ ("holds_scope", ["project:write", "endpoint:read"], ["endpoint:read"], []),
+ ("write_covers_read", ["project:write", "feature_flag:write"], ["feature_flag:read"], []),
+ ("wildcard", ["*"], ["account:read", "loop:write"], []),
+ ]
+ )
+ def test_create_requires_caller_to_hold_requested_scopes(
+ self, _name: str, caller_scopes: list[str], requested_scopes: list[str], missing_scopes: list[str]
+ ) -> None:
+ token = self.create_personal_api_key_with_scopes(caller_scopes)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/project_secret_api_keys/",
+ data={"label": "minted", "scopes": requested_scopes},
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+
+ if missing_scopes:
+ assert response.status_code == 403, response.content
+ assert response.json()["detail"].endswith(f": {', '.join(missing_scopes)}."), response.content
+ else:
+ assert response.status_code == 201, response.content
+ assert ProjectSecretAPIKey.objects.filter(team=self.team, label="minted").exists() == (not missing_scopes)
+
+ @parameterized.expand(
+ [
+ (
+ "adds_unheld_scope",
+ ["endpoint:read"],
+ ["project:write", "endpoint:read"],
+ ["endpoint:read", "account:read"],
+ 403,
+ ),
+ (
+ "adds_held_scope_and_keeps_unheld_scope",
+ ["account:read"],
+ ["project:write", "endpoint:read"],
+ ["account:read", "endpoint:read"],
+ 200,
+ ),
+ (
+ "keeps_and_removes_unheld_scopes",
+ ["endpoint:read", "account:read"],
+ ["project:write"],
+ ["account:read"],
+ 200,
+ ),
+ ]
+ )
+ def test_update_requires_caller_to_hold_added_scopes(
+ self, _name: str, key_scopes: list[str], caller_scopes: list[str], new_scopes: list[str], expected_status: int
+ ) -> None:
+ key = ProjectSecretAPIKey.objects.create(
+ team=self.team,
+ label="existing",
+ secure_value=hash_key_value(generate_random_token_secret()),
+ scopes=key_scopes,
+ created_by=self.user,
+ )
+ token = self.create_personal_api_key_with_scopes(caller_scopes)
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/project_secret_api_keys/{key.id}/",
+ data={"scopes": new_scopes},
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+
+ assert response.status_code == expected_status, response.content
+ key.refresh_from_db()
+ assert key.scopes == (new_scopes if expected_status == 200 else key_scopes)
+
+ def test_roll_rejected_when_caller_lacks_key_scopes(self) -> None:
+ secure_value = hash_key_value(generate_random_token_secret())
+ key = ProjectSecretAPIKey.objects.create(
+ team=self.team,
+ label="existing",
+ secure_value=secure_value,
+ scopes=["endpoint:read", "account:read"],
+ created_by=self.user,
+ )
+ token = self.create_personal_api_key_with_scopes(["project:write", "endpoint:read"])
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/project_secret_api_keys/{key.id}/roll/",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+
+ assert response.status_code == 403, response.content
+ key.refresh_from_db()
+ assert key.secure_value == secure_value
diff --git a/posthog/permissions.py b/posthog/permissions.py
index 20eb2b7e6452..6373522c8f06 100644
--- a/posthog/permissions.py
+++ b/posthog/permissions.py
@@ -41,6 +41,7 @@ from posthog.scopes import (
MCP_BUILT_IN_AGENT_SCOPE,
APIScopeObject,
APIScopeObjectOrNotSupported,
+ scopes_not_covered,
)
from posthog.session.reauth import sensitive_action_reference, step_up_required
from posthog.utils import get_can_create_org
@@ -884,16 +885,10 @@ class APIScopePermission(ScopeBasePermission):
if "*" in key_scopes and scope_object != "INTERNAL" and not action_targets_internal:
return True
- for required_scope in required_scopes:
- valid_scopes = [required_scope]
-
- # For all valid scopes with :read we also add :write
- if required_scope.endswith(":read"):
- valid_scopes.append(required_scope.replace(":read", ":write"))
-
- if not any(scope in key_scopes for scope in valid_scopes):
- self.message = f"API key missing required scope '{required_scope}'"
- return False
+ missing_scopes = scopes_not_covered(key_scopes, required_scopes)
+ if missing_scopes:
+ self.message = f"API key missing required scope '{missing_scopes[0]}'"
+ return False
return True
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 49fbc915a710..6d3848486f03 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -418,6 +418,15 @@ def _with_read_halves(scopes: frozenset[str]) -> frozenset[str]:
return frozenset(scopes | {scope.replace(":write", ":read") for scope in scopes if scope.endswith(":write")})
+def scopes_not_covered(held_scopes: Iterable[str], required_scopes: Iterable[str]) -> list[str]:
+ """The required scopes that the held scopes do not cover, in the order given. A `:write` scope
+ covers the matching `:read`. APIScopePermission and project secret API key issuance share this
+ rule, so an issued key cannot get a scope that the issuing credential cannot use. Callers handle
+ `*` themselves, because APIScopePermission does not let `*` reach INTERNAL scope objects."""
+ covered = _with_read_halves(frozenset(held_scopes))
+ return [scope for scope in required_scopes if scope not in covered]
+
+
def scopes_within_ceiling(
requested: Iterable[str],
app_scopes: Iterable[str],