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: allow organization override of max personal api keys (#124876)

Reece Jonesbe49957ee805
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index cbd454badf03..76a2931deef5 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -6134,6 +6134,8 @@ export interface UserApi {
readonly pending_invites: readonly PendingInviteApi[]
/** True if the user belongs to an organization that a partner provisioned, has not yet acknowledged the access on their account, and has at least one Personal API Key or passkey, or a third-party OAuth application that can currently act as them. Used to gate a one-shot review screen on first post-provisioning login. Becomes False once the user POSTs to `/api/users/@me/credentials_review_complete/`. Read-only. */
readonly requires_credential_review: boolean
+ /** How many personal API keys the user may hold, from the `personal_api_keys` billing entitlement of the user's organizations. The highest limit across their organizations applies, and 10 when no organization grants a limit. Creating a key beyond it is rejected with a validation error. Read-only. */
+ readonly personal_api_keys_limit: number
}
export interface PaginatedUserListApi {
@@ -6250,6 +6252,8 @@ export interface PatchedUserApi {
readonly pending_invites?: readonly PendingInviteApi[]
/** True if the user belongs to an organization that a partner provisioned, has not yet acknowledged the access on their account, and has at least one Personal API Key or passkey, or a third-party OAuth application that can currently act as them. Used to gate a one-shot review screen on first post-provisioning login. Becomes False once the user POSTs to `/api/users/@me/credentials_review_complete/`. Read-only. */
readonly requires_credential_review?: boolean
+ /** How many personal API keys the user may hold, from the `personal_api_keys` billing entitlement of the user's organizations. The highest limit across their organizations applies, and 10 when no organization grants a limit. Creating a key beyond it is rejected with a validation error. Read-only. */
+ readonly personal_api_keys_limit?: number
}
export interface UserGithubLoginApi {
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index f522dcb17411..d651a19124ce 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -2,7 +2,9 @@ import { AGENT_USE_CASE_SCOPES } from 'lib/agentScopes.generated'
import type { APIScopeAction, APIScopeObject } from '~/types'
-export const MAX_API_KEYS_PER_USER = 10 // Same as in posthog/api/personal_api_key.py
+// Fallback when the user has not loaded yet. The real limit comes from the `personal_api_keys`
+// entitlement and travels on the user as `personal_api_keys_limit`.
+export const DEFAULT_MAX_API_KEYS_PER_USER = 10
export type ScopeAccessLevel = 'none' | 'read' | 'write'
diff --git a/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx b/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx
index 2b51c0bcf797..824231d0c725 100644
--- a/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx
+++ b/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx
@@ -25,8 +25,9 @@ import { dayjs } from 'lib/dayjs'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { Link } from 'lib/lemon-ui/Link'
-import { API_KEY_SCOPE_PRESETS, MAX_API_KEYS_PER_USER } from 'lib/scopes'
+import { API_KEY_SCOPE_PRESETS, DEFAULT_MAX_API_KEYS_PER_USER } from 'lib/scopes'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+import { userLogic } from 'scenes/userLogic'
import { PersonalAPIKeyType } from '~/types'
@@ -618,6 +619,8 @@ function PersonalAPIKeysTable(): JSX.Element {
export function PersonalAPIKeys(): JSX.Element {
const { keys, canUsePersonalApiKeys } = useValues(personalAPIKeysLogic)
const { setEditingKeyId } = useActions(personalAPIKeysLogic)
+ const { user } = useValues(userLogic)
+ const keysLimit = user?.personal_api_keys_limit ?? DEFAULT_MAX_API_KEYS_PER_USER
return (
<>
@@ -628,8 +631,8 @@ export function PersonalAPIKeys(): JSX.Element {
disabledReason={
!canUsePersonalApiKeys
? 'Your organization does not allow members using personal API keys.'
- : keys.length >= MAX_API_KEYS_PER_USER
- ? `You can only have ${MAX_API_KEYS_PER_USER} personal API keys. Remove an existing key before creating a new one.`
+ : keys.length >= keysLimit
+ ? `You can only have ${keysLimit} personal API keys. Remove an existing key before creating a new one.`
: false
}
>
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 7be14374226b..d5448a375a90 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -442,6 +442,8 @@ export interface UserType extends UserBaseType {
onboarding_delegated_to_organization_id?: string | null
onboarding_delegation_accepted_at?: string | null
is_organization_first_user?: boolean
+ /** How many personal API keys this user may hold, from the `personal_api_keys` entitlement. */
+ personal_api_keys_limit?: number
pending_invites?: PendingInviteForCurrentUser[]
}
diff --git a/posthog/api/personal_api_key.py b/posthog/api/personal_api_key.py
index 86f431596e32..62bc4b2a310a 100644
--- a/posthog/api/personal_api_key.py
+++ b/posthog/api/personal_api_key.py
@@ -16,7 +16,7 @@ from posthog.auth import PersonalAPIKeyAuthentication, SessionAuthentication
from posthog.helpers.dev_api_key import get_local_dev_api_key_value
from posthog.models import PersonalAPIKey, User
from posthog.models.oauth import has_live_third_party_oauth_access
-from posthog.models.personal_api_key import LEGACY_HASH_PREFIX
+from posthog.models.personal_api_key import LEGACY_HASH_PREFIX, max_personal_api_keys_for_user
from posthog.models.team.team import Team
from posthog.models.utils import generate_random_token_personal, hash_key_value, mask_key_value
from posthog.permissions import TimeSensitiveActionPermission
@@ -24,8 +24,6 @@ from posthog.personal_api_key_minting import mint_personal_api_key
from posthog.scopes import API_SCOPE_ACTIONS, GRANTABLE_API_SCOPE_OBJECTS
from posthog.user_permissions import UserPermissions
-MAX_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."
@@ -222,9 +220,10 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):
request = self.context["request"]
user = request.user
count = PersonalAPIKey.objects.filter(user=user).count()
- if count >= MAX_API_KEYS_PER_USER:
+ limit = max_personal_api_keys_for_user(user)
+ if count >= limit:
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."
+ f"You can only have {limit} personal API keys. Remove an existing key before creating a new one."
)
try:
minted = mint_personal_api_key(
diff --git a/posthog/api/test/test_personal_api_keys.py b/posthog/api/test/test_personal_api_keys.py
index b100e99c1f07..700e0ef40436 100644
--- a/posthog/api/test/test_personal_api_keys.py
+++ b/posthog/api/test/test_personal_api_keys.py
@@ -22,7 +22,7 @@ from posthog.jwt import PosthogJwtAudience, encode_jwt
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
from posthog.models.organization import Organization
-from posthog.models.personal_api_key import LEGACY_PERSONAL_API_KEY_SALT, PersonalAPIKey
+from posthog.models.personal_api_key import LEGACY_PERSONAL_API_KEY_SALT, PersonalAPIKey, max_personal_api_keys_for_user
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.models.utils import SHA256_HASH_PREFIX, generate_random_token_personal, hash_key_value, mask_key_value
@@ -128,12 +128,19 @@ class TestPersonalAPIKeysAPI(APIBaseTest):
assert response.status_code == 201
assert response.json()["description"] is None
- def test_create_too_many_api_keys(self):
- for i in range(0, 10):
- self.client.post(
+ @parameterized.expand([(None, 10), (12, 12)])
+ def test_create_too_many_api_keys(self, entitlement_limit: int | None, expected_limit: int):
+ if entitlement_limit is not None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.PERSONAL_API_KEYS, "name": "Personal API keys", "limit": entitlement_limit}
+ ]
+ self.organization.save()
+ for i in range(0, expected_limit):
+ response = self.client.post(
"/api/personal_api_keys",
{"label": i, "scopes": ["insight:read"], "scoped_organizations": [], "scoped_teams": []},
)
+ assert response.status_code == 201, response.json()
response = self.client.post(
"/api/personal_api_keys",
{"label": i, "scopes": ["insight:read"], "scoped_organizations": [], "scoped_teams": []},
@@ -142,10 +149,26 @@ class TestPersonalAPIKeysAPI(APIBaseTest):
assert response.json() == {
"type": "validation_error",
"code": "invalid_input",
- "detail": "You can only have 10 personal API keys. Remove an existing key before creating a new one.",
+ "detail": f"You can only have {expected_limit} personal API keys. Remove an existing key before creating a new one.",
"attr": None,
}
+ def test_personal_api_key_limit_is_the_highest_entitlement_across_organizations(self):
+ other_organization = Organization.objects.create(name="Other organization")
+ other_organization.members.add(self.user)
+
+ other_organization.available_product_features = [
+ {"key": AvailableFeature.PERSONAL_API_KEYS, "name": "Personal API keys", "limit": 3}
+ ]
+ other_organization.save()
+ assert max_personal_api_keys_for_user(self.user) == 10
+
+ other_organization.available_product_features = [
+ {"key": AvailableFeature.PERSONAL_API_KEYS, "name": "Personal API keys", "limit": 25}
+ ]
+ other_organization.save()
+ assert max_personal_api_keys_for_user(self.user) == 25
+
def test_create_personal_api_key_label_required(self):
response = self.client.post("/api/personal_api_keys/", {"label": ""})
assert response.status_code == 400
diff --git a/posthog/api/user.py b/posthog/api/user.py
index 6332eeac75fb..e4593af99624 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -120,7 +120,7 @@ from posthog.models.organization_domain import OrganizationDomain
from posthog.models.organization_integration import OrganizationIntegration
from posthog.models.organization_notification_lock import notification_locks_for_users
from posthog.models.organization_provisioning import OrganizationProvisioning
-from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.personal_api_key import PersonalAPIKey, max_personal_api_keys_for_user
from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
from posthog.models.user import (
ROLE_CHOICES,
@@ -353,6 +353,14 @@ class UserSerializer(serializers.ModelSerializer):
"choice underneath. Read-only."
),
)
+ personal_api_keys_limit = serializers.SerializerMethodField(
+ help_text=(
+ "How many personal API keys the user may hold, from the `personal_api_keys` billing "
+ "entitlement of the user's organizations. The highest limit across their organizations "
+ "applies, and 10 when no organization grants a limit. Creating a key beyond it is "
+ "rejected with a validation error. Read-only."
+ ),
+ )
class Meta:
model = User
@@ -411,6 +419,7 @@ class UserSerializer(serializers.ModelSerializer):
"pending_invites",
"requires_credential_review",
"notification_locks",
+ "personal_api_keys_limit",
]
read_only_fields = [
@@ -543,6 +552,10 @@ class UserSerializer(serializers.ModelSerializer):
def get_has_social_auth(self, instance: User) -> bool:
return instance.social_auth.exists()
+ @extend_schema_field(serializers.IntegerField())
+ def get_personal_api_keys_limit(self, instance: User) -> int:
+ return max_personal_api_keys_for_user(instance)
+
@tracer.start_as_current_span("user_serializer.requires_credential_review")
def get_requires_credential_review(self, instance: User) -> bool:
if instance.credentials_reviewed_at is not None:
diff --git a/posthog/constants.py b/posthog/constants.py
index 9807591cad0d..9a938b06151d 100644
--- a/posthog/constants.py
+++ b/posthog/constants.py
@@ -62,6 +62,7 @@ class AvailableFeature(StrEnum):
XAA_AUTHENTICATION = "xaa_authentication"
POSTHOG_CODE_USAGE = "posthog_code_usage"
TOOLBAR_HEATMAPS = "toolbar_heatmaps"
+ PERSONAL_API_KEYS = "personal_api_keys"
TREND_FILTER_TYPE_ACTIONS = "actions"
diff --git a/posthog/models/personal_api_key.py b/posthog/models/personal_api_key.py
index fddcf717cb3f..48d9d0afe644 100644
--- a/posthog/models/personal_api_key.py
+++ b/posthog/models/personal_api_key.py
@@ -9,12 +9,14 @@ from django.utils import timezone
from prometheus_client import Counter
+from posthog.constants import AvailableFeature
from posthog.migration_helpers import deprecate_field
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.utils import PERSONAL_API_KEY_PREFIX, EncryptionModeType, generate_random_token, hash_key_value
if TYPE_CHECKING:
from posthog.models.organization import Organization
+ from posthog.models.user import User
HashMode = tuple[EncryptionModeType, Optional[int]]
@@ -28,6 +30,8 @@ PERSONAL_API_KEY_MODES_TO_TRY: tuple[HashMode, ...] = (
LEGACY_PERSONAL_API_KEY_SALT = "posthog_personal_api_key"
LEGACY_HASH_PREFIX = f"{PBKDF2PasswordHasher.algorithm}$"
+DEFAULT_MAX_PERSONAL_API_KEYS = 10
+
PERSONAL_API_KEY_AUTH_COUNTER = Counter(
"personal_api_key_hash_mode_total",
"Successful personal API key authentications by hash mode",
@@ -71,6 +75,22 @@ class PersonalAPIKey(ModelActivityMixin, models.Model):
return self.expires_at is not None and self.expires_at <= timezone.now()
+def max_personal_api_keys_for_user(user: "User") -> int:
+ """How many personal API keys the user may hold.
+
+ A key is not bound to one organization, so the highest `personal_api_keys` limit across the
+ user's organizations applies. Organizations without a numeric limit grant the default.
+ """
+ org_features = user.organization_memberships.values_list("organization__available_product_features", flat=True)
+ limits = [
+ feature.get("limit")
+ for features in org_features
+ for feature in features or []
+ if feature and feature.get("key") == AvailableFeature.PERSONAL_API_KEYS
+ ]
+ return max([DEFAULT_MAX_PERSONAL_API_KEYS, *(limit for limit in limits if isinstance(limit, int))])
+
+
_LEGACY_PERSONAL_API_KEY_PATTERN = re.compile(r"^[A-Za-z0-9_-]{43}$")
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index 744b137660ca..a139a8827069 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -19300,6 +19300,10 @@ export namespace Schemas {
* True if the user belongs to an organization that a partner provisioned, has not yet acknowledged the access on their account, and has at least one Personal API Key or passkey, or a third-party OAuth application that can currently act as them. Used to gate a one-shot review screen on first post-provisioning login. Becomes False once the user POSTs to `/api/users/@me/credentials_review_complete/`. Read-only.
*/
requires_credential_review: boolean;
+ /**
+ * How many personal API keys the user may hold, from the `personal_api_keys` billing entitlement of the user's organizations. The highest limit across their organizations applies, and 10 when no organization grants a limit. Creating a key beyond it is rejected with a validation error. Read-only.
+ */
+ personal_api_keys_limit: number;
};
export type PaginatedUserList = {
count: number;
@@ -20089,6 +20093,7 @@ export namespace Schemas {
active_realtime_notification_types: Array<string>;
pending_invites: Array<PendingInvite>;
requires_credential_review: boolean;
+ personal_api_keys_limit: number;
}>;
export type PersonRecord = {
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a80f80265cdb..f02b4739a474 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -83437,6 +83437,8 @@ export namespace Schemas {
readonly pending_invites: readonly PendingInvite[];
/** True if the user belongs to an organization that a partner provisioned, has not yet acknowledged the access on their account, and has at least one Personal API Key or passkey, or a third-party OAuth application that can currently act as them. Used to gate a one-shot review screen on first post-provisioning login. Becomes False once the user POSTs to `/api/users/@me/credentials_review_complete/`. Read-only. */
readonly requires_credential_review: boolean;
+ /** How many personal API keys the user may hold, from the `personal_api_keys` billing entitlement of the user's organizations. The highest limit across their organizations applies, and 10 when no organization grants a limit. Creating a key beyond it is rejected with a validation error. Read-only. */
+ readonly personal_api_keys_limit: number;
}
export interface PaginatedUserList {
@@ -94458,6 +94460,8 @@ export namespace Schemas {
readonly pending_invites?: readonly PendingInvite[];
/** True if the user belongs to an organization that a partner provisioned, has not yet acknowledged the access on their account, and has at least one Personal API Key or passkey, or a third-party OAuth application that can currently act as them. Used to gate a one-shot review screen on first post-provisioning login. Becomes False once the user POSTs to `/api/users/@me/credentials_review_complete/`. Read-only. */
readonly requires_credential_review?: boolean;
+ /** How many personal API keys the user may hold, from the `personal_api_keys` billing entitlement of the user's organizations. The highest limit across their organizations applies, and 10 when no organization grants a limit. Creating a key beyond it is rejected with a validation error. Read-only. */
+ readonly personal_api_keys_limit?: number;
}
export interface PinnedAccountProperty {