:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(auth): create personal api keys through one function (#114412)
Tom Piccirelloeeba28d7e6cc
diff --git a/.semgrep/rules/security/personal-api-key-mint.py b/.semgrep/rules/security/personal-api-key-mint.pynew file mode 100644index 000000000000..c9de0047053a--- /dev/null+++ b/.semgrep/rules/security/personal-api-key-mint.py@@ -0,0 +1,40 @@+# Test file for the personal-api-key-mint semgrep rules+from posthog.accessible_teams import AccessibleTeams+from posthog.models import PersonalAPIKey+from posthog.personal_api_key_minting import mint_personal_api_key++# ruleid: personal-api-key-created-outside-mint+PersonalAPIKey.objects.create(user=user, label="key", scopes=["*"], scoped_teams=[team.id])++# ruleid: personal-api-key-created-outside-mint+PersonalAPIKey.objects.get_or_create(user=user, label="key")++# ruleid: personal-api-key-created-outside-mint+PersonalAPIKey.objects.update_or_create(user=user, label="key", defaults={"scopes": ["*"]})++# ruleid: personal-api-key-created-outside-mint+PersonalAPIKey.objects.bulk_create([PersonalAPIKey(user=user, label="key")])++# ruleid: personal-api-key-created-outside-mint+key = PersonalAPIKey(user=user, label="key")++# ruleid: personal-api-key-created-outside-mint+user.personal_api_keys.create(label="key", scopes=["*"])++# ok: personal-api-key-created-outside-mint+minted = mint_personal_api_key(user, label="key", scopes=["*"], teams=AccessibleTeams.for_user(user, [team.id]))++# ok: personal-api-key-created-outside-mint+PersonalAPIKey.objects.filter(user=user, label="key").delete()++# ok: personal-api-key-created-outside-mint+existing = PersonalAPIKey.objects.get(secure_value=secure_value)++# ruleid: accessible-teams-built-directly+teams = AccessibleTeams(user_id=user.pk, team_ids=(team.id,), _token=token)++# ok: accessible-teams-built-directly+teams = AccessibleTeams.for_user(user, [team.id])++# ok: accessible-teams-built-directly+teams = AccessibleTeams.all_for(user)diff --git a/.semgrep/rules/security/personal-api-key-mint.yaml b/.semgrep/rules/security/personal-api-key-mint.yamlnew file mode 100644index 000000000000..c61b0cb4bef9--- /dev/null+++ b/.semgrep/rules/security/personal-api-key-mint.yaml@@ -0,0 +1,44 @@+rules:+ - id: personal-api-key-created-outside-mint+ pattern-either:+ - pattern: PersonalAPIKey(...)+ - pattern: PersonalAPIKey.objects.create(...)+ - pattern: PersonalAPIKey.objects.bulk_create(...)+ - pattern: PersonalAPIKey.objects.get_or_create(...)+ - pattern: PersonalAPIKey.objects.update_or_create(...)+ - pattern: $OWNER.personal_api_keys.create(...)+ - pattern: $OWNER.personal_api_keys.get_or_create(...)+ - pattern: $OWNER.personal_api_keys.update_or_create(...)+ message: >+ Create personal API keys with `mint_personal_api_key` from+ `posthog.personal_api_key_minting`. It takes the team scope as an+ `AccessibleTeams`, which is built only after the owner's project access+ is checked, so no key can reach a team its owner cannot use. If a key+ genuinely cannot go through it (for example a dev seed with a fixed+ value), add `# nosemgrep: personal-api-key-created-outside-mint` on the+ line before, with the reason.+ severity: ERROR+ languages: [python]+ paths:+ exclude:+ - '**/test*/**'+ - '**/tests/**'+ - '**/test_*.py'+ - '**/*_test.py'+ - '**/conftest.py'+ - '**/migrations/**'+ - '**/.semgrep/**'+ - '/posthog/personal_api_key_minting.py'+ - id: accessible-teams-built-directly+ pattern: AccessibleTeams(...)+ message: >+ Build `AccessibleTeams` with `for_user`, `for_request` or `all_for`. Those+ constructors run the project access check; direct construction skips it+ and raises at runtime.+ severity: ERROR+ languages: [python]+ paths:+ exclude:+ - '**/migrations/**'+ - '**/.semgrep/**'+ - '/posthog/accessible_teams.py'diff --git a/bin/hobby-ci-setup-user.py b/bin/hobby-ci-setup-user.pyindex e6a81e98e3da..1a1cb1809312 100644--- a/bin/hobby-ci-setup-user.py+++ b/bin/hobby-ci-setup-user.py@@ -14,8 +14,9 @@ import djangoos.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")django.setup()+from posthog.accessible_teams import AccessibleTeams # noqa: E402from posthog.models import Organization, PersonalAPIKey, Team, User # noqa: E402-from posthog.models.utils import generate_random_token_personal, hash_key_value, mask_key_value # noqa: E402+from posthog.personal_api_key_minting import mint_personal_api_key # noqa: E402org = Organization.objects.first()if not org:@@ -31,13 +32,10 @@ user = User.objects.filter(email="[email protected]").first()if not user:user = User.objects.create_and_join(org, "[email protected]", "CiTest123!", "Hobby CI")-raw_key = generate_random_token_personal()PersonalAPIKey.objects.filter(user=user, label="ci-smoke-test").delete()-PersonalAPIKey.objects.create(- user=user,+minted = mint_personal_api_key(+ user,label="ci-smoke-test",- secure_value=hash_key_value(raw_key),- mask_value=mask_key_value(raw_key),scopes=["query:read","logs:read",@@ -46,5 +44,6 @@ PersonalAPIKey.objects.create("tracing:read","feature_flag:write",],+ teams=AccessibleTeams.all_for(user),)-print(f"{team.api_token}|||{raw_key}") # noqa: T201+print(f"{team.api_token}|||{minted.value}") # noqa: T201diff --git a/ee/api/agentic_provisioning/credentials.py b/ee/api/agentic_provisioning/credentials.pyindex deb9a3326c45..c8ecebf06693 100644--- a/ee/api/agentic_provisioning/credentials.py+++ b/ee/api/agentic_provisioning/credentials.py@@ -4,12 +4,12 @@ from __future__ import annotationsimport unicodedata+from posthog.accessible_teams import AccessibleTeamsfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.oauth import OAuthApplication-from posthog.models.personal_api_key import PersonalAPIKey, hash_key_valuefrom posthog.models.team.team import Teamfrom posthog.models.user import User-from posthog.models.utils import generate_random_token_personal, mask_key_value+from posthog.personal_api_key_minting import mint_personal_api_keyfrom posthog.scopes import narrow_scopes_to_ceilingfrom ee.api.agentic_provisioning.analytics import capture_provisioning_event@@ -98,23 +98,20 @@ def maybe_create_provisioned_pat(return Nonetry:- api_key_value = generate_random_token_personal()label_base = f"{label_prefix} - {team.name}" if label_prefix else team.name# PersonalAPIKey.label is stored as a CharField(max_length=40); cap the# final string to match so we never violate the column constraint.label = label_base[:PROVISIONED_PAT_LABEL_MAX_LENGTH]- PersonalAPIKey.objects.create(- user=user,+ minted = mint_personal_api_key(+ user,label=label,- secure_value=hash_key_value(api_key_value),- mask_value=mask_key_value(api_key_value),scopes=pat_scopes,- scoped_teams=[team.id],- scoped_organizations=[str(team.organization_id)],+ teams=AccessibleTeams.for_user(user, [team.id]),+ organization_ids=[str(team.organization_id)],)- return api_key_value+ return minted.valueexcept Exception:capture_exception(additional_properties={"user_id": user.id, "team_id": team.id})return Nonediff --git a/ee/partners/stripe/api/provisioning/core.py b/ee/partners/stripe/api/provisioning/core.pyindex ed76b8251860..e0bb64783426 100644--- a/ee/partners/stripe/api/provisioning/core.py+++ b/ee/partners/stripe/api/provisioning/core.py@@ -19,17 +19,17 @@ from django.utils.http import url_has_allowed_host_and_schemeimport structlog+from posthog.accessible_teams import AccessibleTeamsfrom posthog.api.authentication import password_reset_token_generatorfrom posthog.event_usage import report_user_signed_upfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.email_utils import EmailLookupHandlerfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshTokenfrom posthog.models.organization_provisioning import OrganizationProvisioning-from posthog.models.personal_api_key import PersonalAPIKey, hash_key_valuefrom posthog.models.team.team import Teamfrom posthog.models.team.team_provisioning_config import TeamProvisioningConfigfrom posthog.models.user import User-from posthog.models.utils import generate_random_token_personal, mask_key_value+from posthog.personal_api_key_minting import mint_personal_api_keyfrom posthog.tasks.email import send_provisioning_welcomefrom products.access_control.backend.facade.user_access_control import UserAccessControl@@ -672,23 +672,20 @@ def maybe_create_provisioned_pat(# target only provisioned keys - scope alone is ambiguous with keys a user# created via /api/personal_api_keys/ carrying the same team/org scope.try:- api_key_value = generate_random_token_personal()label_base = f"{label_prefix} - {team.name}" if label_prefix else team.name# PersonalAPIKey.label is stored as a CharField(max_length=40); cap the# final string to match so we never violate the column constraint.label = label_base[:PROVISIONED_PAT_LABEL_MAX_LENGTH]- PersonalAPIKey.objects.create(- user=user,+ minted = mint_personal_api_key(+ user,label=label,- secure_value=hash_key_value(api_key_value),- mask_value=mask_key_value(api_key_value),scopes=pat_scopes,- scoped_teams=[team.id],- scoped_organizations=[str(team.organization_id)],+ teams=AccessibleTeams.for_user(user, [team.id]),+ organization_ids=[str(team.organization_id)],)- return api_key_value+ return minted.valueexcept Exception:capture_exception(additional_properties={"user_id": user.id, "team_id": team.id})return Nonediff --git a/posthog/accessible_teams.py b/posthog/accessible_teams.pynew file mode 100644index 000000000000..d9dedc6e0f91--- /dev/null+++ b/posthog/accessible_teams.py@@ -0,0 +1,86 @@+from collections.abc import Sequence+from dataclasses import field+from typing import Self, cast++from rest_framework.request import Request++from posthog.dataclasses import frozen+from posthog.models import Team, User+from posthog.permissions import get_authenticator_scoped_organization_ids, get_authenticator_scoped_team_ids+from posthog.user_permissions import UserPermissions++_CONSTRUCTION_TOKEN = object()+++class CredentialScopeDenied(Exception):+ pass+++@frozen+class AccessibleTeams:+ """The teams one user may scope a credential to.++ Only the classmethods build an instance, and each runs the project access check first, so code+ that receives an instance knows the check ran for `user_id`. Direct construction raises.+ """++ user_id: int+ # None means no team restriction: the request-time permission checks decide which teams the+ # credential reaches each time it is used.+ team_ids: tuple[int, ...] | None+ _token: object = field(repr=False, compare=False)++ def __post_init__(self) -> None:+ if self._token is not _CONSTRUCTION_TOKEN:+ raise TypeError("Build AccessibleTeams with for_user, for_request or all_for.")++ @classmethod+ def for_user(cls, user: User, team_ids: Sequence[int]) -> Self:+ requested = tuple(dict.fromkeys(team_ids))+ if not requested:+ raise ValueError("Pass at least one team id, or use all_for for no team restriction.")++ teams = list(Team.objects.filter(pk__in=requested))+ if len(teams) != len(requested):+ raise CredentialScopeDenied("One or more teams do not exist.")++ user_permissions = UserPermissions(user)+ if any(user_permissions.team(team).effective_membership_level is None for team in teams):+ raise CredentialScopeDenied("The user cannot access one or more teams.")++ return cls(user_id=user.pk, team_ids=requested, _token=_CONSTRUCTION_TOKEN)++ @classmethod+ def for_request(cls, request: Request, team_ids: Sequence[int] | None) -> Self:+ """Like `for_user`, but also confined to the orgs and teams that the request's credential reaches.++ `None` asks for no team restriction. Only a credential without an organization or team+ restriction can grant that, because a key confined to some orgs or teams must not hand+ out a wider one.+ """+ user = cast(User, request.user)+ authenticator = getattr(request, "successful_authenticator", None)+ credential_team_ids = get_authenticator_scoped_team_ids(authenticator)+ credential_organization_ids = get_authenticator_scoped_organization_ids(authenticator)++ if team_ids is None:+ if credential_team_ids is not None or credential_organization_ids is not None:+ raise CredentialScopeDenied("A credential confined to some orgs or teams cannot grant all of them.")+ return cls.all_for(user)++ if credential_team_ids is not None and not set(team_ids) <= set(credential_team_ids):+ raise CredentialScopeDenied("The credential does not reach one or more teams.")++ if credential_organization_ids is not None:+ allowed_organization_ids = {str(org_id) for org_id in credential_organization_ids}+ requested_organization_ids = {+ str(org_id) for org_id in Team.objects.filter(pk__in=team_ids).values_list("organization_id", flat=True)+ }+ if not requested_organization_ids or not requested_organization_ids <= allowed_organization_ids:+ raise CredentialScopeDenied("The credential does not reach one or more organizations.")++ return cls.for_user(user, team_ids)++ @classmethod+ def all_for(cls, user: User) -> Self:+ return cls(user_id=user.pk, team_ids=None, _token=_CONSTRUCTION_TOKEN)diff --git a/posthog/api/cli_auth.py b/posthog/api/cli_auth.pyindex 1476ca20cc06..99f88be7c265 100644--- a/posthog/api/cli_auth.py+++ b/posthog/api/cli_auth.py@@ -23,12 +23,12 @@ from rest_framework.decorators import actionfrom rest_framework.permissions import AllowAny, IsAuthenticatedfrom rest_framework.response import Response+from posthog.accessible_teams import AccessibleTeams, CredentialScopeDeniedfrom posthog.api.personal_api_key import validate_personal_api_key_scopesfrom posthog.auth import SessionAuthenticationfrom posthog.models import PersonalAPIKey, Team, User-from posthog.models.utils import generate_random_token_personal, hash_key_value, mask_key_value+from posthog.personal_api_key_minting import mint_personal_api_keyfrom posthog.scopes import UNPRIVILEGED_SCOPES-from posthog.user_permissions import UserPermissions# Device code lives for 10 minutesDEVICE_CODE_EXPIRY_SECONDS = 600@@ -243,24 +243,21 @@ class CLIAuthViewSet(viewsets.ViewSet):status=status.HTTP_400_BAD_REQUEST,)- # Verify user has access to the projecttry:team = Team.objects.get(id=project_id)- if UserPermissions(user).team(team).effective_membership_level is None:- return Response(- {"error": "access_denied", "error_description": "You do not have access to this project"},- status=status.HTTP_403_FORBIDDEN,- )except Team.DoesNotExist:return Response({"error": "invalid_project", "error_description": "Project not found"},status=status.HTTP_400_BAD_REQUEST,)- # Create Personal API Key for the CLI- api_key_value = generate_random_token_personal()- mask_value = mask_key_value(api_key_value)- secure_value = hash_key_value(api_key_value)+ try:+ teams = AccessibleTeams.for_request(request, [team.id])+ except CredentialScopeDenied:+ return Response(+ {"error": "access_denied", "error_description": "You do not have access to this project"},+ status=status.HTTP_403_FORBIDDEN,+ )# Label max length is 40 chars, so truncate if neededtimestamp = timezone.now().strftime("%Y-%m-%d %H:%M")@@ -270,15 +267,7 @@ class CLIAuthViewSet(viewsets.ViewSet):had_prior_pat = PersonalAPIKey.objects.filter(user=user).exists()- PersonalAPIKey.objects.create(- user=user,- label=label,- secure_value=secure_value,- mask_value=mask_value,- scopes=scopes,- scoped_teams=[team.id],- scoped_organizations=[],- )+ minted = mint_personal_api_key(user, label=label, scopes=scopes, teams=teams)# User explicitly authorized this CLI via SessionAuthentication (see# CLIAuthViewSet.get_authenticators - authorize is session-only). If they@@ -292,7 +281,7 @@ class CLIAuthViewSet(viewsets.ViewSet):# Mark device as authorized and store the API keydevice_data["status"] = "authorized"- device_data["personal_api_key"] = api_key_value+ device_data["personal_api_key"] = minted.valuedevice_data["label"] = labeldevice_data["project_id"] = str(project_id)device_data["scopes"] = scopes@@ -306,7 +295,7 @@ class CLIAuthViewSet(viewsets.ViewSet):{"status": "success","label": label,- "mask_value": mask_value,+ "mask_value": minted.key.mask_value,},status=status.HTTP_200_OK,)diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex f845fe735fb8..c7e284b96daa 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -48,7 +48,7 @@ from posthog.models.oauth import (revoke_application_sessions,revoke_oauth_session,)-from posthog.models.organization import Organization+from posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.team.team import Teamfrom posthog.scopes import ALL_SCOPES, ALWAYS_ALLOWED_SCOPES, MIN_SCOPES_BEFORE_TRUNCATION, get_oauth_scopes_supportedfrom posthog.settings.utils import generate_rsa_private_key_pem@@ -5079,6 +5079,16 @@ class TestOAuthAPI(APIBaseTest):@time_machine.travel("2025-01-01 00:00:00", tick=False)def test_token_response_derives_scoped_teams_for_first_party_app(self):+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ restricted_team = Team.objects.create(organization=self.organization, name="Restricted Team")+ AccessControl.objects.create(+ team=restricted_team, resource="project", resource_id=str(restricted_team.id), access_level="none"+ )app = self._create_first_party_app(slug="first-party-derive")grant = OAuthGrant.objects.create(application=app,@@ -5106,6 +5116,7 @@ class TestOAuthAPI(APIBaseTest):data = response.json()self.assertEqual(data["scoped_organizations"], [str(self.organization.id)])self.assertIn(self.team.pk, data["scoped_teams"])+ self.assertNotIn(restricted_team.pk, data["scoped_teams"])access_token = OAuthAccessToken.objects.get(token=data["access_token"])self.assertEqual(access_token.scoped_teams, [])diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex af9aa2e36b70..92ee6c533e5d 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -2272,16 +2272,24 @@ class OAuthTokenView(TokenView):# to populate the project selector. When the app is org-scoped only,# access_token.scoped_teams is empty in the DB by design — derive teams# from scoped_organizations so clients keep working without weakening- # the stored token scope.+ # the stored token scope. List only the teams the user can access, because+ # access control can deny an org member some of the org's teams.# TODO(@charlesvien): remove this after a migration period in PostHog Desktop.if (not scoped_teamsand scoped_organizationsand access_token.applicationand access_token.application.is_first_party+ and access_token.user):- scoped_teams = list(- Team.objects.filter(organization_id__in=scoped_organizations).values_list("pk", flat=True)+ candidate_teams = Team.objects.filter(organization_id__in=scoped_organizations).only(+ "pk", "organization_id", "project_id"+ )+ user_permissions = UserPermissions(access_token.user)+ scoped_teams = sorted(+ team.pk+ for team in candidate_teams+ if user_permissions.team(team).effective_membership_level is not None)response_data["scoped_teams"] = scoped_teamsdiff --git a/posthog/api/personal_api_key.py b/posthog/api/personal_api_key.pyindex ac97b9bf2b49..37294041dbcd 100644--- a/posthog/api/personal_api_key.py+++ b/posthog/api/personal_api_key.py@@ -8,6 +8,7 @@ from drf_spectacular.utils import extend_schema, extend_schema_fieldfrom rest_framework import response, serializers, status, viewsetsfrom rest_framework.permissions import BasePermission, IsAuthenticated+from posthog.accessible_teams import AccessibleTeams, CredentialScopeDeniedfrom posthog.api.utils import actionfrom posthog.auth import PersonalAPIKeyAuthentication, SessionAuthenticationfrom posthog.helpers.dev_api_key import get_local_dev_api_key_value@@ -17,11 +18,15 @@ from posthog.models.personal_api_key import LEGACY_HASH_PREFIXfrom posthog.models.team.team import Teamfrom posthog.models.utils import generate_random_token_personal, hash_key_value, mask_key_valuefrom posthog.permissions import TimeSensitiveActionPermission+from posthog.personal_api_key_minting import mint_personal_api_keyfrom posthog.scopes import API_SCOPE_ACTIONS, GRANTABLE_API_SCOPE_OBJECTSfrom posthog.user_permissions import UserPermissionsMAX_API_KEYS_PER_USER = 10 # Same as in scopes.tsx+SCOPED_TEAMS_ACCESS_ERROR = "You must be a member of all teams that you are scoping the key to."+SCOPE_ACCESS_ERROR = "You must be a member of all teams and organizations that you are scoping the key to."+def validate_personal_api_key_scopes(scopes: list[str],@@ -148,19 +153,12 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):return scopesdef validate_scoped_teams(self, scoped_teams):- requesting_user: User = self.context["request"].user- user_permissions = UserPermissions(requesting_user)-- teams = Team.objects.filter(pk__in=scoped_teams)-- if len(teams) != len(scoped_teams):- raise serializers.ValidationError(f"You must be a member of all teams that you are scoping the key to.")-- for team in teams:- if user_permissions.team(team).effective_membership_level is None:- raise serializers.ValidationError(f"You must be a member of all teams that you are scoping the key to.")+ try:+ AccessibleTeams.for_request(self.context["request"], scoped_teams or None)+ except CredentialScopeDenied:+ raise serializers.ValidationError(SCOPED_TEAMS_ACCESS_ERROR) from None- return scoped_teams+ return list(dict.fromkeys(scoped_teams))def validate_scoped_organizations(self, scoped_organizations):requesting_user: User = self.context["request"].user@@ -181,19 +179,26 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):return scoped_organizationsdef create(self, validated_data: dict, **kwargs) -> PersonalAPIKey:- user = self.context["request"].user+ request = self.context["request"]+ user = request.usercount = PersonalAPIKey.objects.filter(user=user).count()if count >= MAX_API_KEYS_PER_USER:raise serializers.ValidationError(f"You can only have {MAX_API_KEYS_PER_USER} personal API keys. Remove an existing key before creating a new one.")- value = generate_random_token_personal()- mask_value = mask_key_value(value)- secure_value = hash_key_value(value)- personal_api_key = PersonalAPIKey.objects.create(- user=user, secure_value=secure_value, mask_value=mask_value, **validated_data- )- personal_api_key._value = value # type: ignore+ try:+ minted = mint_personal_api_key(+ user,+ label=validated_data["label"],+ description=validated_data.get("description"),+ scopes=validated_data["scopes"],+ teams=AccessibleTeams.for_request(request, validated_data.get("scoped_teams") or None),+ organization_ids=validated_data.get("scoped_organizations") or [],+ )+ except CredentialScopeDenied:+ raise serializers.ValidationError(SCOPE_ACCESS_ERROR) from None+ personal_api_key = minted.key+ personal_api_key._value = minted.value # type: ignore# User created their FIRST PAT themselves through a session, so the credential# review interstitial has nothing partner-issued to surface for them - mark it# acknowledged. Four gates, all load-bearing:@@ -207,7 +212,6 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):# - no live third-party OAuth access: a partner-provisioned account has access# to disclose even with no partner-issued PAT, and stamping here would retire# the interstitial before the user was ever shown that connection.- request = self.context["request"]if (count == 0and user.credentials_reviewed_at is Nonediff --git a/posthog/api/test/test_personal_api_keys.py b/posthog/api/test/test_personal_api_keys.pyindex 967745548e70..7b8117cd9eca 100644--- a/posthog/api/test/test_personal_api_keys.py+++ b/posthog/api/test/test_personal_api_keys.py@@ -174,13 +174,17 @@ class TestPersonalAPIKeysAPI(APIBaseTest):],)response = self.client.patch(- f"/api/personal_api_keys/{key.id}", {"label": "test-update", "scopes": ["insight:write"]}+ f"/api/personal_api_keys/{key.id}",+ {"label": "test-update", "scopes": ["insight:write"], "scoped_teams": [self.team.id, self.team.id]},)assert response.status_code == 200data = response.json()assert data["id"] == key.idassert data["label"] == "test-update"assert data["scopes"] == ["insight:write"]+ assert data["scoped_teams"] == [self.team.id]+ key.refresh_from_db()+ assert key.scoped_teams == [self.team.id]def test_allows_all_scope(self):response = self.client.post(diff --git a/posthog/management/commands/setup_dev.py b/posthog/management/commands/setup_dev.pyindex d932717840f9..8128f6e5ef99 100644--- a/posthog/management/commands/setup_dev.py+++ b/posthog/management/commands/setup_dev.py@@ -50,6 +50,7 @@ class Command(BaseCommand):PropertyDefinition.objects.create(name="name", type=PropertyDefinition.Type.PERSON, team=team)PropertyDefinition.objects.create(name="is_demo", type=PropertyDefinition.Type.PERSON, team=team)+ # nosemgrep: personal-api-key-created-outside-mint -- this dev seed uses a fixed, known key value, and the mint always generates a random onePersonalAPIKey.objects.create(user=user,label="e2e_demo_api_key key",diff --git a/posthog/management/commands/setup_local_api_key.py b/posthog/management/commands/setup_local_api_key.pyindex 7358355be090..4095f32bd97d 100644--- a/posthog/management/commands/setup_local_api_key.py+++ b/posthog/management/commands/setup_local_api_key.py@@ -109,6 +109,7 @@ class Command(BaseCommand):create_scopes = scopes if scopes is not None else add_scopes+ # nosemgrep: personal-api-key-created-outside-mint -- the local dev key has a fixed value that survives database resets, and the mint always generates a random onePersonalAPIKey.objects.create(user=user,label=DEV_KEY_LABEL,diff --git a/posthog/personal_api_key_minting.py b/posthog/personal_api_key_minting.pynew file mode 100644index 000000000000..03896bbe379e--- /dev/null+++ b/posthog/personal_api_key_minting.py@@ -0,0 +1,64 @@+import uuid+from collections.abc import Sequence+from dataclasses import field++from posthog.accessible_teams import AccessibleTeams, CredentialScopeDenied+from posthog.dataclasses import frozen+from posthog.models import OrganizationMembership, PersonalAPIKey, User+from posthog.models.utils import generate_random_token_personal, hash_key_value, mask_key_value+++@frozen+class MintedPersonalAPIKey:+ key: PersonalAPIKey+ value: str = field(repr=False)+++def mint_personal_api_key(+ owner: User,+ *,+ label: str,+ scopes: Sequence[str],+ teams: AccessibleTeams,+ organization_ids: Sequence[str] = (),+ description: str | None = None,+) -> MintedPersonalAPIKey:+ """Insert a personal API key and return it with its raw value.++ This is the only code that creates a personal API key (the `personal-api-key-created-outside-mint`+ semgrep rule enforces it), so the team scope of every key comes from an `AccessibleTeams` that+ was checked for the key's owner.+ """+ if teams.user_id != owner.pk:+ raise CredentialScopeDenied("The team scope was checked for a different user.")+ _check_organization_scope(owner, organization_ids)++ value = generate_random_token_personal()+ key = PersonalAPIKey.objects.create(+ user=owner,+ label=label,+ description=description,+ secure_value=hash_key_value(value),+ mask_value=mask_key_value(value),+ scopes=list(scopes),+ scoped_teams=list(teams.team_ids or []),+ scoped_organizations=list(organization_ids),+ )+ return MintedPersonalAPIKey(key=key, value=value)+++def _check_organization_scope(owner: User, organization_ids: Sequence[str]) -> None:+ try:+ requested = {uuid.UUID(str(organization_id)) for organization_id in organization_ids}+ except ValueError:+ raise CredentialScopeDenied("One or more organization ids are not valid.") from None+ if not requested:+ return++ member_of = set(+ OrganizationMembership.objects.filter(user=owner, organization_id__in=requested).values_list(+ "organization_id", flat=True+ )+ )+ if not requested <= member_of:+ raise CredentialScopeDenied("The owner is not a member of one or more organizations.")diff --git a/posthog/test/test_accessible_teams.py b/posthog/test/test_accessible_teams.pynew file mode 100644index 000000000000..9b56f8ba082d--- /dev/null+++ b/posthog/test/test_accessible_teams.py@@ -0,0 +1,110 @@+from types import SimpleNamespace+from typing import cast++import pytest+from posthog.test.base import BaseTest++from parameterized import parameterized+from rest_framework.request import Request++from posthog.accessible_teams import AccessibleTeams, CredentialScopeDenied+from posthog.auth import PersonalAPIKeyAuthentication+from posthog.constants import AvailableFeature+from posthog.models import Organization, OrganizationMembership, PersonalAPIKey, Team+from posthog.models.utils import generate_random_token_personal, hash_key_value++from products.access_control.backend.models.access_control import AccessControl+++class TestAccessibleTeams(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ self.open_team = Team.objects.create(organization=self.organization, name="Open Team")+ self.restricted_team = Team.objects.create(organization=self.organization, name="Restricted Team")+ AccessControl.objects.create(+ team=self.restricted_team,+ resource="project",+ resource_id=str(self.restricted_team.id),+ access_level="none",+ )++ def _request(+ self,+ *,+ credential_team_ids: list[int] | None = None,+ credential_organization_ids: list[str] | None = None,+ ) -> Request:+ authenticator: PersonalAPIKeyAuthentication | None = None+ if credential_team_ids is not None or credential_organization_ids is not None:+ authenticator = PersonalAPIKeyAuthentication()+ authenticator.personal_api_key = PersonalAPIKey.objects.create(+ user=self.user,+ label="scoped",+ secure_value=hash_key_value(generate_random_token_personal()),+ scopes=["*"],+ scoped_teams=credential_team_ids or [],+ scoped_organizations=credential_organization_ids or [],+ )+ return cast(Request, SimpleNamespace(user=self.user, successful_authenticator=authenticator))++ @parameterized.expand(+ [+ ("accessible_team", "open", None, True),+ ("restricted_team", "restricted", None, False),+ ("missing_team", "missing", None, False),+ ("team_inside_credential", "open", "open", True),+ ("team_outside_credential", "open", "self_team", False),+ ("all_teams_from_session", "all", None, True),+ ("all_teams_from_confined_credential", "all", "self_team", False),+ ]+ )+ def test_for_request_grants_only_teams_that_user_and_credential_reach(+ self, _name: str, requested: str, credential: str | None, allowed: bool+ ) -> None:+ team_ids_by_name = {+ "open": [self.open_team.id],+ "restricted": [self.restricted_team.id],+ "missing": [self.restricted_team.id + 10_000],+ "self_team": [self.team.id],+ }+ requested_team_ids = None if requested == "all" else team_ids_by_name[requested]+ request = self._request(credential_team_ids=team_ids_by_name[credential] if credential else None)++ if allowed:+ teams = AccessibleTeams.for_request(request, requested_team_ids)+ self.assertEqual(teams.user_id, self.user.pk)+ self.assertEqual(teams.team_ids, tuple(requested_team_ids) if requested_team_ids else None)+ else:+ with pytest.raises(CredentialScopeDenied):+ AccessibleTeams.for_request(request, requested_team_ids)++ def test_for_request_denies_team_outside_credential_scoped_organizations(self) -> None:+ other_organization = Organization.objects.create(name="Other")+ OrganizationMembership.objects.create(+ user=self.user, organization=other_organization, level=OrganizationMembership.Level.MEMBER+ )+ other_team = Team.objects.create(organization=other_organization, name="Other Open Team")+ request = self._request(credential_organization_ids=[str(self.organization.id)])+ with pytest.raises(CredentialScopeDenied):+ AccessibleTeams.for_request(request, [other_team.id])++ def test_for_request_allows_team_inside_credential_scoped_organizations(self) -> None:+ request = self._request(credential_organization_ids=[str(self.organization.id)])+ teams = AccessibleTeams.for_request(request, [self.open_team.id])+ self.assertEqual(teams.team_ids, (self.open_team.id,))++ def test_for_request_denies_all_teams_from_org_confined_credential(self) -> None:+ request = self._request(credential_organization_ids=[str(self.organization.id)])+ with pytest.raises(CredentialScopeDenied):+ AccessibleTeams.for_request(request, None)++ def test_direct_construction_raises(self) -> None:+ with pytest.raises(TypeError):+ # nosemgrep: accessible-teams-built-directly -- this test proves that direct construction raises+ AccessibleTeams(user_id=self.user.pk, team_ids=(self.restricted_team.id,), _token=object())diff --git a/posthog/test/test_personal_api_key_minting.py b/posthog/test/test_personal_api_key_minting.pynew file mode 100644index 000000000000..978e80bea50e--- /dev/null+++ b/posthog/test/test_personal_api_key_minting.py@@ -0,0 +1,39 @@+import pytest+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.accessible_teams import AccessibleTeams, CredentialScopeDenied+from posthog.models import Organization, PersonalAPIKey, User+from posthog.personal_api_key_minting import mint_personal_api_key+++class TestMintPersonalAPIKey(BaseTest):+ @parameterized.expand(+ [+ ("teams_checked_for_another_user", "other_user_teams", "own_organization"),+ ("organization_owner_is_not_in", "own_teams", "other_organization"),+ ]+ )+ def test_refuses_scope_not_checked_for_the_owner(self, _name: str, teams: str, organization: str) -> None:+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)+ other_organization = Organization.objects.create(name="Other Organization")+ teams_by_name = {+ "own_teams": AccessibleTeams.for_user(self.user, [self.team.id]),+ "other_user_teams": AccessibleTeams.for_user(other_user, [self.team.id]),+ }+ organization_ids_by_name = {+ "own_organization": [str(self.organization.id)],+ "other_organization": [str(other_organization.id)],+ }++ with pytest.raises(CredentialScopeDenied):+ mint_personal_api_key(+ self.user,+ label="key",+ scopes=["*"],+ teams=teams_by_name[teams],+ organization_ids=organization_ids_by_name[organization],+ )++ self.assertFalse(PersonalAPIKey.objects.filter(user=self.user).exists())diff --git a/products/skills/backend/marketplace/credentials.py b/products/skills/backend/marketplace/credentials.pyindex 26154eb80125..d2bbb425bf01 100644--- a/products/skills/backend/marketplace/credentials.py+++ b/products/skills/backend/marketplace/credentials.py@@ -21,8 +21,10 @@ from urllib.parse import quotefrom django.db import transactionfrom django.utils import timezone+from posthog.accessible_teams import AccessibleTeamsfrom posthog.models import PersonalAPIKey, Team, Userfrom posthog.models.utils import generate_random_token_personal, hash_key_value, mask_key_value+from posthog.personal_api_key_minting import mint_personal_api_keyfrom posthog.utils import absolute_uri# Read-only: a leaked credential can only read this one team's skills, nothing else.@@ -69,19 +71,16 @@ def issue_marketplace_credential(team: Team, user: User, *, rotate: bool) -> Issexisting.save(update_fields=narrowed_fields)return IssuedMarketplaceCredential(key=existing, token=None, status="exists")- raw_token = generate_random_token_personal()if existing is None:- key = PersonalAPIKey.objects.create(- user=user,+ minted = mint_personal_api_key(+ user,label=label,- secure_value=hash_key_value(raw_token),- mask_value=mask_key_value(raw_token),- scopes=list(MARKETPLACE_CREDENTIAL_SCOPES),- scoped_teams=[team.id],- scoped_organizations=[],+ scopes=MARKETPLACE_CREDENTIAL_SCOPES,+ teams=AccessibleTeams.for_user(user, [team.id]),)- return IssuedMarketplaceCredential(key=key, token=raw_token, status="created")+ return IssuedMarketplaceCredential(key=minted.key, token=minted.value, status="created")+ raw_token = generate_random_token_personal()existing.secure_value = hash_key_value(raw_token)existing.mask_value = mask_key_value(raw_token)existing.last_used_at = Nonediff --git a/products/tasks/scripts/run_agent_in_docker.py b/products/tasks/scripts/run_agent_in_docker.pyindex 9ee2f254c570..13df4201c0f7 100755--- a/products/tasks/scripts/run_agent_in_docker.py+++ b/products/tasks/scripts/run_agent_in_docker.py@@ -24,8 +24,9 @@ django.setup()from django.db import transaction+from posthog.accessible_teams import AccessibleTeamsfrom posthog.models import Integration, PersonalAPIKey, Team, User-from posthog.models.utils import generate_random_token_personal, hash_key_value+from posthog.personal_api_key_minting import mint_personal_api_keyfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.tasks.backend.logic.services.docker_sandbox import DockerSandbox@@ -80,11 +81,9 @@ def create_test_task(repository=None):task_run = TaskRun.objects.create(task=task, team=team)- api_key_value = generate_random_token_personal()- api_key = PersonalAPIKey.objects.create(- user=user,+ minted = mint_personal_api_key(+ user,label="Test runAgent",- secure_value=hash_key_value(api_key_value),scopes=["error_tracking:read","user:read",@@ -93,8 +92,10 @@ def create_test_task(repository=None):"task:read","task:write",],- scoped_teams=[team.id],+ teams=AccessibleTeams.for_user(user, [team.id]),)+ api_key = minted.key+ api_key_value = minted.valueprint(f"✓ Created test task: {task.id}")print(f" - Run ID: {task_run.id}")