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(settings): show admins personal API keys with org access (#62103)

Yasenfb7c9f3510e6
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index 36621d7de9c8..5a1a2f1856ea 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -140,6 +140,7 @@ import { OrganizationAI } from './organization/OrgAI'
import { OrganizationAITrainingOptOut } from './organization/OrgAITraining'
import { OrganizationDangerZone } from './organization/OrganizationDangerZone'
import { OrganizationIntegrations } from './organization/OrganizationIntegrations'
+import { OrganizationPersonalAPIKeys } from './organization/OrganizationPersonalAPIKeys'
import { OrganizationSecuritySettings } from './organization/OrganizationSecuritySettings'
import { OrganizationDisplayName } from './organization/OrgDisplayName'
import { OrgIPAnonymizationDefault } from './organization/OrgIPAnonymizationDefault'
@@ -1716,6 +1717,7 @@ export const SETTINGS_MAP: SettingSection[] = [
level: 'organization',
id: 'organization-security',
title: 'Security',
+ minimumAccessLevel: OrganizationMembershipLevel.Admin,
settings: [
{
id: 'organization-security',
@@ -1725,6 +1727,14 @@ export const SETTINGS_MAP: SettingSection[] = [
component: <OrganizationSecuritySettings />,
keywords: ['password', 'session', 'timeout', 'compliance', 'sharing', 'public'],
},
+ {
+ id: 'organization-personal-api-keys',
+ title: 'Personal API key access',
+ description:
+ "See which members' personal API keys can reach this organization or its projects, who owns them, and the scopes they grant.",
+ component: <OrganizationPersonalAPIKeys />,
+ keywords: ['api key', 'personal', 'token', 'access', 'audit'],
+ },
],
},
{
diff --git a/frontend/src/scenes/settings/organization/OrganizationPersonalAPIKeys.tsx b/frontend/src/scenes/settings/organization/OrganizationPersonalAPIKeys.tsx
new file mode 100644
index 000000000000..1c12ff590a1c
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/OrganizationPersonalAPIKeys.tsx
@@ -0,0 +1,85 @@
+import { useValues } from 'kea'
+
+import { PayGateMini } from 'lib/components/PayGateMini/PayGateMini'
+import { useRestrictedArea } from 'lib/components/RestrictedArea'
+import { TZLabel } from 'lib/components/TZLabel'
+import { OrganizationMembershipLevel } from 'lib/constants'
+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { fullName } from 'lib/utils'
+import { TagList } from 'scenes/settings/user/PersonalAPIKeys'
+
+import { AvailableFeature } from '~/types'
+
+import type { OrganizationPersonalAPIKeyApi } from 'products/platform_features/frontend/generated/api.schemas'
+
+import { organizationPersonalAPIKeysLogic } from './organizationPersonalAPIKeysLogic'
+
+function AccessScope({ accessScope }: { accessScope: OrganizationPersonalAPIKeyApi['access_scope'] }): JSX.Element {
+ if (accessScope.type === 'all') {
+ return <span className="text-muted">All projects (unscoped)</span>
+ }
+ if (accessScope.type === 'organization') {
+ return <span>Organization-wide</span>
+ }
+ return <TagList tags={(accessScope.projects ?? []).map((project) => project.name)} />
+}
+
+export function OrganizationPersonalAPIKeys(): JSX.Element {
+ const { keys, keysLoading } = useValues(organizationPersonalAPIKeysLogic)
+ const restrictionReason = useRestrictedArea({ minimumAccessLevel: OrganizationMembershipLevel.Admin })
+
+ if (restrictionReason) {
+ return <p className="text-muted">{restrictionReason}</p>
+ }
+
+ const columns: LemonTableColumns<OrganizationPersonalAPIKeyApi> = [
+ {
+ title: 'Owner',
+ key: 'owner',
+ render: (_, key) => (
+ <div className="flex flex-col">
+ <span>{fullName(key.owner) || key.owner.email}</span>
+ <span className="text-muted text-xs">{key.owner.email}</span>
+ </div>
+ ),
+ },
+ {
+ title: 'Masked value',
+ key: 'mask_value',
+ render: (_, key) => <span className="font-mono">{key.mask_value}</span>,
+ },
+ {
+ title: 'Scopes',
+ key: 'scopes',
+ render: (_, key) => <TagList tags={[...key.scopes]} />,
+ },
+ {
+ title: 'Access scope',
+ key: 'access_scope',
+ render: (_, key) => <AccessScope accessScope={key.access_scope} />,
+ },
+ {
+ title: 'Last used',
+ key: 'last_used_at',
+ render: (_, key) =>
+ key.last_used_at ? <TZLabel time={key.last_used_at} /> : <span className="text-muted">Never</span>,
+ },
+ {
+ title: 'Created',
+ key: 'created_at',
+ render: (_, key) => <TZLabel time={key.created_at} />,
+ },
+ ]
+
+ return (
+ <PayGateMini feature={AvailableFeature.ORGANIZATION_SECURITY_SETTINGS}>
+ <LemonTable
+ dataSource={keys}
+ loading={keysLoading}
+ columns={columns}
+ rowKey={(key) => `${key.owner.email}-${key.mask_value}-${key.created_at}`}
+ emptyState="No personal API keys have access to this organization."
+ />
+ </PayGateMini>
+ )
+}
diff --git a/frontend/src/scenes/settings/organization/organizationPersonalAPIKeysLogic.test.ts b/frontend/src/scenes/settings/organization/organizationPersonalAPIKeysLogic.test.ts
new file mode 100644
index 000000000000..c28b75aeaf36
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/organizationPersonalAPIKeysLogic.test.ts
@@ -0,0 +1,57 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { organizationPersonalAPIKeysLogic } from './organizationPersonalAPIKeysLogic'
+
+const MOCK_KEYS = [
+ {
+ owner: { first_name: 'Ada', last_name: 'Lovelace', email: '[email protected]' },
+ mask_value: 'phx_***1234',
+ scopes: ['insight:read'],
+ access_scope: { type: 'all' },
+ last_used_at: null,
+ created_at: '2026-01-01T00:00:00Z',
+ },
+ {
+ owner: { first_name: 'Alan', last_name: 'Turing', email: '[email protected]' },
+ mask_value: 'phx_***5678',
+ scopes: ['feature_flag:write'],
+ access_scope: { type: 'projects', projects: [{ id: 1, name: 'Default project' }] },
+ last_used_at: '2026-02-01T00:00:00Z',
+ created_at: '2026-01-15T00:00:00Z',
+ },
+]
+
+describe('organizationPersonalAPIKeysLogic', () => {
+ let logic: ReturnType<typeof organizationPersonalAPIKeysLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/organizations/:organization_id/personal_api_keys/': {
+ count: MOCK_KEYS.length,
+ next: null,
+ previous: null,
+ results: MOCK_KEYS,
+ },
+ },
+ })
+ initKeaTests()
+ logic = organizationPersonalAPIKeysLogic()
+ logic.mount()
+ })
+
+ it('loads keys on mount', async () => {
+ await expectLogic(logic).toDispatchActions(['loadKeys', 'loadKeysSuccess']).toMatchValues({
+ keys: MOCK_KEYS,
+ keysLoading: false,
+ })
+ })
+
+ it('starts with empty array and loading state', () => {
+ expect(logic.values.keys).toEqual([])
+ expect(logic.values.keysLoading).toEqual(true)
+ })
+})
diff --git a/frontend/src/scenes/settings/organization/organizationPersonalAPIKeysLogic.ts b/frontend/src/scenes/settings/organization/organizationPersonalAPIKeysLogic.ts
new file mode 100644
index 000000000000..edb86e91a55a
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/organizationPersonalAPIKeysLogic.ts
@@ -0,0 +1,28 @@
+import { afterMount, kea, path } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api, { ApiConfig } from 'lib/api'
+
+import { getPersonalApiKeysListUrl } from 'products/platform_features/frontend/generated/api'
+import type { OrganizationPersonalAPIKeyApi } from 'products/platform_features/frontend/generated/api.schemas'
+
+import type { organizationPersonalAPIKeysLogicType } from './organizationPersonalAPIKeysLogicType'
+
+export const organizationPersonalAPIKeysLogic = kea<organizationPersonalAPIKeysLogicType>([
+ path(['scenes', 'settings', 'organization', 'organizationPersonalAPIKeysLogic']),
+ loaders({
+ keys: [
+ [] as OrganizationPersonalAPIKeyApi[],
+ {
+ loadKeys: async () => {
+ // Page through everything — an incomplete list would be a security-audit blind spot.
+ const url = getPersonalApiKeysListUrl(ApiConfig.getCurrentOrganizationId())
+ return await api.loadPaginatedResults<OrganizationPersonalAPIKeyApi>(url)
+ },
+ },
+ ],
+ }),
+ afterMount(({ actions }) => {
+ actions.loadKeys()
+ }),
+])
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index 171c5f9f1345..4061ab6d79b2 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -198,6 +198,7 @@ export type SettingId =
| 'organization-proxy'
| 'organization-roles'
| 'organization-security'
+ | 'organization-personal-api-keys'
| 'passkeys'
| 'path-cleaning'
| 'person-display-name'
diff --git a/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx b/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx
index 16d336ec87c5..4ec38025d5a0 100644
--- a/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx
+++ b/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx
@@ -261,7 +261,7 @@ export function EditKeyModal({ zIndex }: EditKeyModalProps): JSX.Element {
)
}
-type TagListProps = { onMoreClick: () => void; tags: string[] }
+type TagListProps = { onMoreClick?: () => void; tags: string[] }
export function TagList({ tags, onMoreClick }: TagListProps): JSX.Element {
return (
@@ -273,7 +273,7 @@ export function TagList({ tags, onMoreClick }: TagListProps): JSX.Element {
))}
{tags.length > 4 && (
<Tooltip title={tags.slice(4).join(', ')}>
- <LemonTag onClick={onMoreClick} forceClickable>
+ <LemonTag onClick={onMoreClick} forceClickable={!!onMoreClick}>
+{tags.length - 4} more
</LemonTag>
</Tooltip>
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.py
index a7cee12bf3a0..4c9528d0dcc7 100644
--- a/posthog/api/__init__.py
+++ b/posthog/api/__init__.py
@@ -61,6 +61,7 @@ from . import (
organization_integration,
organization_invite,
organization_member,
+ organization_personal_api_key,
personal_api_key,
project_secret_api_key,
proxy_record,
@@ -414,6 +415,12 @@ organizations_router.register(
"organization_domains",
["organization_id"],
)
+organizations_router.register(
+ r"personal_api_keys",
+ organization_personal_api_key.OrganizationPersonalAPIKeyViewSet,
+ "organization_personal_api_keys",
+ ["organization_id"],
+)
organizations_router.register(
r"cimd_verification_tokens",
cimd_verification_token.CIMDVerificationTokenViewSet,
diff --git a/posthog/api/organization_personal_api_key.py b/posthog/api/organization_personal_api_key.py
new file mode 100644
index 000000000000..0e0038357b45
--- /dev/null
+++ b/posthog/api/organization_personal_api_key.py
@@ -0,0 +1,97 @@
+from typing import Any
+
+from django.db.models import QuerySet
+
+from drf_spectacular.utils import extend_schema, extend_schema_field
+from rest_framework import mixins, serializers, viewsets
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models.personal_api_key import PersonalAPIKey, get_organization_personal_api_keys
+from posthog.permissions import OrganizationAdminReadPermissions
+
+
+class OrganizationPersonalAPIKeyOwnerSerializer(serializers.Serializer):
+ first_name = serializers.CharField(read_only=True, help_text="First name of the key's owner.")
+ last_name = serializers.CharField(read_only=True, help_text="Last name of the key's owner.")
+ email = serializers.EmailField(read_only=True, help_text="Email address of the key's owner.")
+
+
+class OrganizationPersonalAPIKeyProjectScopeSerializer(serializers.Serializer):
+ id = serializers.IntegerField(help_text="Project (team) ID the key is scoped to.")
+ name = serializers.CharField(help_text="Name of the project the key is scoped to.")
+
+
+class OrganizationPersonalAPIKeyAccessScopeSerializer(serializers.Serializer):
+ type = serializers.CharField(
+ help_text="Breadth of access: 'all' (every project the owner can reach), 'organization' "
+ "(this whole organization), or 'projects' (specific projects listed under 'projects')."
+ )
+ projects = OrganizationPersonalAPIKeyProjectScopeSerializer(
+ many=True,
+ required=False,
+ help_text="Projects within this organization the key is scoped to, present only when type is 'projects'.",
+ )
+
+
+class OrganizationPersonalAPIKeySerializer(serializers.ModelSerializer):
+ owner = OrganizationPersonalAPIKeyOwnerSerializer(
+ source="user", read_only=True, help_text="The organization member who owns this key."
+ )
+ mask_value = serializers.CharField(
+ read_only=True,
+ help_text="Masked, display-safe hint of the key value (e.g. 'phx_***1234'). Not the secret. "
+ "The owner sees the same masked value in their own settings, so it can be used to identify a key.",
+ )
+ scopes = serializers.ListField(
+ child=serializers.CharField(),
+ read_only=True,
+ help_text="API scopes granted to the key, e.g. 'insight:read'. A single '*' means full access.",
+ )
+ access_scope = serializers.SerializerMethodField(help_text="Where the key's scopes apply within this organization.")
+ last_used_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="When the key was last used to authenticate, if ever."
+ )
+ created_at = serializers.DateTimeField(read_only=True, help_text="When the key was created.")
+
+ class Meta:
+ model = PersonalAPIKey
+ fields = ["owner", "mask_value", "scopes", "access_scope", "last_used_at", "created_at"]
+ read_only_fields = fields
+
+ @extend_schema_field(OrganizationPersonalAPIKeyAccessScopeSerializer)
+ def get_access_scope(self, key: PersonalAPIKey) -> dict[str, Any]:
+ team_names: dict[int, str] = self.context["team_names"]
+
+ if key.scoped_teams:
+ projects = [
+ {"id": team_id, "name": team_names[team_id]} for team_id in key.scoped_teams if team_id in team_names
+ ]
+ if projects:
+ return {"type": "projects", "projects": projects}
+
+ if not key.scoped_organizations and not key.scoped_teams:
+ return {"type": "all"}
+
+ return {"type": "organization"}
+
+
+@extend_schema(extensions={"x-product": "platform_features"})
+class OrganizationPersonalAPIKeyViewSet(
+ TeamAndOrgViewSetMixin,
+ mixins.ListModelMixin,
+ viewsets.GenericViewSet,
+):
+ scope_object = "INTERNAL"
+ serializer_class = OrganizationPersonalAPIKeySerializer
+ permission_classes = [OrganizationAdminReadPermissions]
+ queryset = PersonalAPIKey.objects.none()
+ # PersonalAPIKey has no organization_id; the parent lookup resolves through the owner's membership.
+ filter_rewrite_rules = {"organization_id": "user__organization_membership__organization_id"}
+
+ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
+ return get_organization_personal_api_keys(self.organization).order_by("-last_used_at", "-created_at")
+
+ def get_serializer_context(self) -> dict[str, Any]:
+ context = super().get_serializer_context()
+ context["team_names"] = {team.id: team.name for team in self.organization.teams.all()}
+ return context
diff --git a/posthog/api/test/test_organization_personal_api_key.py b/posthog/api/test/test_organization_personal_api_key.py
new file mode 100644
index 000000000000..4b7a7d517549
--- /dev/null
+++ b/posthog/api/test/test_organization_personal_api_key.py
@@ -0,0 +1,81 @@
+from posthog.test.base import APIBaseTest
+
+from rest_framework import status
+
+from posthog.models import Organization, OrganizationMembership, PersonalAPIKey, Team, User
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+
+class TestOrganizationPersonalAPIKeyAPI(APIBaseTest):
+ def _create_key(self, user, **kwargs):
+ return PersonalAPIKey.objects.create(
+ user=user,
+ label=kwargs.pop("label", "key"),
+ secure_value=hash_key_value(generate_random_token_personal()),
+ scopes=kwargs.pop("scopes", ["insight:read"]),
+ **kwargs,
+ )
+
+ def _url(self, org=None):
+ return f"/api/organizations/{(org or self.organization).id}/personal_api_keys/"
+
+ def _set_level(self, level):
+ self.organization_membership.level = level
+ self.organization_membership.save()
+
+ def test_admin_can_list_member_keys(self):
+ self._set_level(OrganizationMembership.Level.ADMIN)
+ member = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self._create_key(member, label="member-key")
+
+ response = self.client.get(self._url())
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["count"] == 1
+
+ def test_owner_can_list(self):
+ self._set_level(OrganizationMembership.Level.OWNER)
+ response = self.client.get(self._url())
+ assert response.status_code == status.HTTP_200_OK
+
+ def test_plain_member_is_forbidden(self):
+ self._set_level(OrganizationMembership.Level.MEMBER)
+ response = self.client.get(self._url())
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_response_never_exposes_secret_or_label(self):
+ self._set_level(OrganizationMembership.Level.ADMIN)
+ self._create_key(self.user, label="super-secret-label")
+
+ response = self.client.get(self._url())
+
+ body = response.json()
+ assert response.status_code == status.HTTP_200_OK
+ row = body["results"][0]
+ assert "label" not in row
+ assert "secure_value" not in row
+ assert "value" not in row
+ assert set(row.keys()) == {"owner", "mask_value", "scopes", "access_scope", "last_used_at", "created_at"}
+ assert row["owner"]["email"] == self.user.email
+
+ def test_access_scope_values(self):
+ self._set_level(OrganizationMembership.Level.ADMIN)
+ self._create_key(self.user, label="unscoped")
+ self._create_key(self.user, label="org", scoped_organizations=[str(self.organization.id)])
+ self._create_key(self.user, label="team", scoped_teams=[self.team.id])
+
+ results = self.client.get(self._url()).json()["results"]
+ scope_types = {r["access_scope"]["type"] for r in results}
+
+ assert scope_types == {"all", "organization", "projects"}
+ projects_row = next(r for r in results if r["access_scope"]["type"] == "projects")
+ assert projects_row["access_scope"]["projects"] == [{"id": self.team.id, "name": self.team.name}]
+
+ def test_excludes_other_org_keys(self):
+ self._set_level(OrganizationMembership.Level.ADMIN)
+ other_org = Organization.objects.create(name="other")
+ Team.objects.create(organization=other_org, name="t")
+ outsider = User.objects.create_and_join(other_org, "[email protected]", None)
+ self._create_key(outsider, label="outsider")
+
+ assert self.client.get(self._url()).json()["count"] == 0
diff --git a/posthog/models/personal_api_key.py b/posthog/models/personal_api_key.py
index d958507a935a..0a26ff6996d7 100644
--- a/posthog/models/personal_api_key.py
+++ b/posthog/models/personal_api_key.py
@@ -1,8 +1,9 @@
-from typing import Optional
+from typing import TYPE_CHECKING, Optional
from django.contrib.auth.hashers import PBKDF2PasswordHasher
from django.contrib.postgres.fields import ArrayField
from django.db import models
+from django.db.models import Q, QuerySet
from django.utils import timezone
from django_deprecate_fields import deprecate_field
@@ -11,6 +12,9 @@ from prometheus_client import Counter
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.utils import EncryptionModeType, generate_random_token, hash_key_value
+if TYPE_CHECKING:
+ from posthog.models.organization import Organization
+
PERSONAL_API_KEY_MODES_TO_TRY: tuple[tuple[EncryptionModeType, Optional[int]], ...] = (
("sha256", None), # Moved to simple hashing in 2024-02
("pbkdf2", 260000), # This is the iteration count used by PostHog since the beginning of time.
@@ -72,3 +76,25 @@ def find_personal_api_key(token: str) -> tuple[PersonalAPIKey, str] | None:
pass
return None
+
+
+def get_organization_personal_api_keys(organization: "Organization") -> QuerySet[PersonalAPIKey]:
+ """Personal API keys of org members that can access this organization or any of its projects.
+
+ Includes fully unscoped keys (which can reach everything the owner can), keys explicitly scoped
+ to this organization, and keys scoped to any of the organization's teams.
+ """
+ team_ids = list(organization.teams.values_list("id", flat=True))
+ return (
+ PersonalAPIKey.objects.filter(user__organization_membership__organization_id=organization.id)
+ .filter(
+ Q(scoped_organizations__contains=[str(organization.id)])
+ | Q(scoped_teams__overlap=team_ids)
+ | (
+ (Q(scoped_organizations__isnull=True) | Q(scoped_organizations=[]))
+ & (Q(scoped_teams__isnull=True) | Q(scoped_teams=[]))
+ )
+ )
+ .select_related("user")
+ .distinct()
+ )
diff --git a/posthog/permissions.py b/posthog/permissions.py
index b0a314a64b0c..5beaa7a0f833 100644
--- a/posthog/permissions.py
+++ b/posthog/permissions.py
@@ -178,6 +178,36 @@ class OrganizationAdminWritePermissions(BasePermission):
return membership.level >= OrganizationMembership.Level.ADMIN
+class OrganizationAdminReadPermissions(BasePermission):
+ """
+ Require organization admin or owner level for ALL access, including reads.
+ Unlike `OrganizationAdminWritePermissions`, this does not allow plain members read access.
+ Must always be used **after** `OrganizationMemberPermissions` (which is always required).
+ """
+
+ message = "Your organization access level is insufficient."
+
+ def has_permission(self, request: Request, view) -> bool:
+ organization = get_organization_from_view(view)
+
+ try:
+ membership = OrganizationMembership.objects.get(user=cast(User, request.user), organization=organization)
+ except OrganizationMembership.DoesNotExist:
+ raise NotFound("Organization not found.")
+
+ return membership.level >= OrganizationMembership.Level.ADMIN
+
+ def has_object_permission(self, request: Request, view, object: Model) -> bool:
+ organization = extract_organization(object, view)
+
+ try:
+ membership = OrganizationMembership.objects.get(user=cast(User, request.user), organization=organization)
+ except OrganizationMembership.DoesNotExist:
+ raise NotFound("Organization not found.")
+
+ return membership.level >= OrganizationMembership.Level.ADMIN
+
+
class TeamMemberAccessPermission(BasePermission):
"""Require effective project membership for any access at all."""
diff --git a/posthog/test/test_personal_api_key_org_access.py b/posthog/test/test_personal_api_key_org_access.py
new file mode 100644
index 000000000000..d714dbd18e60
--- /dev/null
+++ b/posthog/test/test_personal_api_key_org_access.py
@@ -0,0 +1,53 @@
+from posthog.test.base import BaseTest
+
+from posthog.models import Organization, Team, User
+from posthog.models.personal_api_key import PersonalAPIKey, get_organization_personal_api_keys
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+
+class TestGetOrganizationPersonalAPIKeys(BaseTest):
+ def _create_key(self, user, scoped_organizations=None, scoped_teams=None, label="key"):
+ return PersonalAPIKey.objects.create(
+ user=user,
+ label=label,
+ secure_value=hash_key_value(generate_random_token_personal()),
+ scopes=["insight:read"],
+ scoped_organizations=scoped_organizations,
+ scoped_teams=scoped_teams,
+ )
+
+ def test_includes_unscoped_org_scoped_and_team_scoped_member_keys(self):
+ member = User.objects.create_and_join(self.organization, "[email protected]", None)
+ unscoped = self._create_key(member, label="unscoped")
+ org_scoped = self._create_key(member, scoped_organizations=[str(self.organization.id)], label="org")
+ team_scoped = self._create_key(member, scoped_teams=[self.team.id], label="team")
+
+ result_ids = set(get_organization_personal_api_keys(self.organization).values_list("id", flat=True))
+
+ assert result_ids == {unscoped.id, org_scoped.id, team_scoped.id}
+
+ def test_excludes_keys_scoped_to_other_org_and_other_teams(self):
+ member = User.objects.create_and_join(self.organization, "[email protected]", None)
+ other_org = Organization.objects.create(name="other")
+ other_team = Team.objects.create(organization=other_org, name="other team")
+ self._create_key(member, scoped_organizations=[str(other_org.id)], label="other-org")
+ self._create_key(member, scoped_teams=[other_team.id], label="other-team")
+
+ assert get_organization_personal_api_keys(self.organization).count() == 0
+
+ def test_excludes_keys_of_non_members(self):
+ outsider = User.objects.create(email="[email protected]")
+ self._create_key(outsider, label="outsider-unscoped")
+
+ assert get_organization_personal_api_keys(self.organization).count() == 0
+
+ def test_deduplicates(self):
+ member = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self._create_key(
+ member,
+ scoped_organizations=[str(self.organization.id)],
+ scoped_teams=[self.team.id],
+ label="both",
+ )
+
+ assert get_organization_personal_api_keys(self.organization).count() == 1
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index f63ec4bc2c42..a4454402c89c 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -326,6 +326,56 @@ export interface PatchedOrganizationMemberApi {
readonly last_login?: string
}
+export interface OrganizationPersonalAPIKeyOwnerApi {
+ /** First name of the key's owner. */
+ readonly first_name: string
+ /** Last name of the key's owner. */
+ readonly last_name: string
+ /** Email address of the key's owner. */
+ readonly email: string
+}
+
+export interface OrganizationPersonalAPIKeyProjectScopeApi {
+ /** Project (team) ID the key is scoped to. */
+ id: number
+ /** Name of the project the key is scoped to. */
+ name: string
+}
+
+export interface OrganizationPersonalAPIKeyAccessScopeApi {
+ /** Breadth of access: 'all' (every project the owner can reach), 'organization' (this whole organization), or 'projects' (specific projects listed under 'projects'). */
+ type: string
+ /** Projects within this organization the key is scoped to, present only when type is 'projects'. */
+ projects?: OrganizationPersonalAPIKeyProjectScopeApi[]
+}
+
+export interface OrganizationPersonalAPIKeyApi {
+ /** The organization member who owns this key. */
+ readonly owner: OrganizationPersonalAPIKeyOwnerApi
+ /** Masked, display-safe hint of the key value (e.g. 'phx_***1234'). Not the secret. The owner sees the same masked value in their own settings, so it can be used to identify a key. */
+ readonly mask_value: string
+ /** API scopes granted to the key, e.g. 'insight:read'. A single '*' means full access. */
+ readonly scopes: readonly string[]
+ /** Where the key's scopes apply within this organization. */
+ readonly access_scope: OrganizationPersonalAPIKeyAccessScopeApi
+ /**
+ * When the key was last used to authenticate, if ever.
+ * @nullable
+ */
+ readonly last_used_at: string | null
+ /** When the key was created. */
+ readonly created_at: string
+}
+
+export interface PaginatedOrganizationPersonalAPIKeyListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: OrganizationPersonalAPIKeyApi[]
+}
+
export type RoleApiMembersItem = { [key: string]: unknown }
export interface RoleApi {
@@ -811,6 +861,17 @@ export type MembersListParams = {
search?: string
}
+export type PersonalApiKeysListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type RolesListParams = {
/**
* Number of results to return per page.
diff --git a/products/platform_features/frontend/generated/api.ts b/products/platform_features/frontend/generated/api.ts
index fdd18e8422d5..98a7a9a9919f 100644
--- a/products/platform_features/frontend/generated/api.ts
+++ b/products/platform_features/frontend/generated/api.ts
@@ -29,6 +29,7 @@ import type {
PaginatedCommentListApi,
PaginatedOrganizationListApi,
PaginatedOrganizationMemberListApi,
+ PaginatedOrganizationPersonalAPIKeyListApi,
PaginatedRoleListApi,
PaginatedRoleMembershipListApi,
PatchedApprovalPolicyApi,
@@ -37,6 +38,7 @@ import type {
PatchedOrganizationMemberApi,
PatchedPinnedSceneTabsApi,
PatchedRoleApi,
+ PersonalApiKeysListParams,
PinnedSceneTabsApi,
PromotedProductIntentApi,
RoleApi,
@@ -249,6 +251,33 @@ export const membersScopedApiKeysRetrieve = async (
})
}
+export const getPersonalApiKeysListUrl = (organizationId: string, params?: PersonalApiKeysListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/organizations/${organizationId}/personal_api_keys/?${stringifiedParams}`
+ : `/api/organizations/${organizationId}/personal_api_keys/`
+}
+
+export const personalApiKeysList = async (
+ organizationId: string,
+ params?: PersonalApiKeysListParams,
+ options?: RequestInit
+): Promise<PaginatedOrganizationPersonalAPIKeyListApi> => {
+ return apiMutator<PaginatedOrganizationPersonalAPIKeyListApi>(getPersonalApiKeysListUrl(organizationId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getRolesListUrl = (organizationId: string, params?: RolesListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/platform_features/mcp/tools.yaml b/products/platform_features/mcp/tools.yaml
index a8e3c41dfdce..7810b1dbf560 100644
--- a/products/platform_features/mcp/tools.yaml
+++ b/products/platform_features/mcp/tools.yaml
@@ -328,6 +328,9 @@ tools:
organizations-update:
operation: update
enabled: false
+ personal-api-keys-list:
+ operation: personal_api_keys_list
+ enabled: false
promoted-product-intent-get:
operation: environments_promoted_product_intent_retrieve
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4d71c45b1bc1..6d7da8570161 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -23611,6 +23611,47 @@ export namespace Schemas {
readonly updated: string;
}
+ export interface OrganizationPersonalAPIKeyOwner {
+ /** First name of the key's owner. */
+ readonly first_name: string;
+ /** Last name of the key's owner. */
+ readonly last_name: string;
+ /** Email address of the key's owner. */
+ readonly email: string;
+ }
+
+ export interface OrganizationPersonalAPIKeyProjectScope {
+ /** Project (team) ID the key is scoped to. */
+ id: number;
+ /** Name of the project the key is scoped to. */
+ name: string;
+ }
+
+ export interface OrganizationPersonalAPIKeyAccessScope {
+ /** Breadth of access: 'all' (every project the owner can reach), 'organization' (this whole organization), or 'projects' (specific projects listed under 'projects'). */
+ type: string;
+ /** Projects within this organization the key is scoped to, present only when type is 'projects'. */
+ projects?: OrganizationPersonalAPIKeyProjectScope[];
+ }
+
+ export interface OrganizationPersonalAPIKey {
+ /** The organization member who owns this key. */
+ readonly owner: OrganizationPersonalAPIKeyOwner;
+ /** Masked, display-safe hint of the key value (e.g. 'phx_***1234'). Not the secret. The owner sees the same masked value in their own settings, so it can be used to identify a key. */
+ readonly mask_value: string;
+ /** API scopes granted to the key, e.g. 'insight:read'. A single '*' means full access. */
+ readonly scopes: readonly string[];
+ /** Where the key's scopes apply within this organization. */
+ readonly access_scope: OrganizationPersonalAPIKeyAccessScope;
+ /**
+ * When the key was last used to authenticate, if ever.
+ * @nullable
+ */
+ readonly last_used_at: string | null;
+ /** When the key was created. */
+ readonly created_at: string;
+ }
+
/**
* * `error_tracking` - Error Tracking
* `eval_clusters` - Eval Clusters
@@ -24729,6 +24770,15 @@ export namespace Schemas {
results: OrganizationOAuthApplication[];
}
+ export interface PaginatedOrganizationPersonalAPIKeyList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: OrganizationPersonalAPIKey[];
+ }
+
export interface ParserRecipe {
readonly id: string;
/**
@@ -46285,6 +46335,17 @@ export namespace Schemas {
offset?: number;
};
+ export type PersonalApiKeysListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type OrganizationsProjectsListParams = {
/**
* Number of results to return per page.