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(auth): show credential review only to partner-provisioned accounts (#118848)

Rafael Audibert2f347d81d79c
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 491cacfd1ed1..605e1f06dc23 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -6101,7 +6101,7 @@ export interface UserApi {
/** Real-time notification types that currently have a live dispatch site. Drives the in-app notifications settings UI. Read-only. */
readonly active_realtime_notification_types: readonly string[]
readonly pending_invites: readonly PendingInviteApi[]
- /** True if the user has at least one Personal API Key or passkey, or a third-party OAuth application that can currently act as them, and has not yet acknowledged that access. 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. */
+ /** 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
}
@@ -6217,7 +6217,7 @@ export interface PatchedUserApi {
/** Real-time notification types that currently have a live dispatch site. Drives the in-app notifications settings UI. Read-only. */
readonly active_realtime_notification_types?: readonly string[]
readonly pending_invites?: readonly PendingInviteApi[]
- /** True if the user has at least one Personal API Key or passkey, or a third-party OAuth application that can currently act as them, and has not yet acknowledged that access. 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. */
+ /** 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
}
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.py
index 3cef6cc38eee..9761cf92353b 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -2373,15 +2373,19 @@ class TestTimeSensitivePermissions(APIBaseTest):
res = self.client.patch("/api/users/@me", payload, format="json")
assert res.status_code != 403, f"Field update should not require re-authentication, got: {res.json()}"
- def test_user_can_update_hedgehog_config_without_recent_authentication(self):
+ @parameterized.expand(
+ [
+ ("hedgehog_config", "patch", "/api/users/@me/hedgehog_config", {"enabled": True, "color": "red"}, 200),
+ ("credentials_review_complete", "post", "/api/users/@me/credentials_review_complete/", {}, 204),
+ ]
+ )
+ def test_user_actions_allowed_without_recent_authentication(
+ self, _name: str, method: str, url: str, payload: dict[str, object], expected_status: int
+ ):
now = datetime.now()
with time_machine.travel(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10), tick=False):
- res = self.client.patch(
- "/api/users/@me/hedgehog_config",
- {"enabled": True, "color": "red"},
- format="json",
- )
- assert res.status_code == 200
+ res = getattr(self.client, method)(url, payload, format="json")
+ assert res.status_code == expected_status, res.content
def test_user_can_update_scene_personalisation_without_recent_authentication(self):
from products.dashboards.backend.models.dashboard import Dashboard
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.py
index 5c893e5fe4b5..4d864c6f1926 100644
--- a/posthog/api/test/test_user.py
+++ b/posthog/api/test/test_user.py
@@ -3,7 +3,7 @@ import time
import uuid
import datetime
from datetime import timedelta
-from typing import Any, cast
+from typing import Any, Literal, cast
from urllib.parse import quote, unquote, urlparse
import pytest
@@ -38,7 +38,10 @@ from posthog.models.instance_setting import set_instance_setting
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthGrant, OAuthRefreshToken
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
+from posthog.models.organization_integration import OrganizationIntegration
+from posthog.models.organization_provisioning import OrganizationProvisioning
from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.models.webauthn_credential import WebauthnCredential
from posthog.temporal.tests.delete_teams.inline import execute_deletion_workflows_inline
@@ -64,6 +67,9 @@ def issue_verification_code(user: User, target_email: str | None = None) -> str:
return mock_send.call_args[0][1]
+ProvisionedBy = Literal["organization", "team", "vercel_installation", "vercel_connectable"]
+
+
class TestUserAPI(APIBaseTest):
new_org: Organization = None # type: ignore
new_project: Team = None # type: ignore
@@ -307,26 +313,47 @@ class TestUserAPI(APIBaseTest):
assert "active_realtime_notification_types" in body
assert "comment_mention" in body["active_realtime_notification_types"]
+ def _provision_organization(self, provisioned_by: ProvisionedBy | None = "organization") -> None:
+ if provisioned_by == "organization":
+ OrganizationProvisioning.objects.create(
+ organization=self.organization, partner=OrganizationProvisioning.Partner.VERCEL
+ )
+ elif provisioned_by == "team":
+ TeamProvisioningConfig.objects.create(team=self.team)
+ elif provisioned_by in ("vercel_installation", "vercel_connectable"):
+ OrganizationIntegration.objects.create(
+ organization=self.organization,
+ kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,
+ integration_id="icfg_test",
+ config={"type": "connectable"} if provisioned_by == "vercel_connectable" else {},
+ )
+
@parameterized.expand(
[
- ("unreviewed_nothing", False, False, False, False),
- ("unreviewed_pat_only", False, True, False, True),
- ("unreviewed_passkey_only", False, False, True, True),
- ("unreviewed_pat_and_passkey", False, True, True, True),
- ("reviewed_pat_only", True, True, False, False),
- ("reviewed_passkey_only", True, False, True, False),
- ("reviewed_pat_and_passkey", True, True, True, False),
- ("reviewed_nothing", True, False, False, False),
+ ("unreviewed_nothing", "organization", False, False, False, False),
+ ("unreviewed_pat_only", "organization", False, True, False, True),
+ ("unreviewed_passkey_only", "organization", False, False, True, True),
+ ("unreviewed_pat_and_passkey", "organization", False, True, True, True),
+ ("unreviewed_pat_only_legacy_team_provisioning", "team", False, True, False, True),
+ ("unreviewed_pat_only_legacy_vercel_installation", "vercel_installation", False, True, False, True),
+ ("unreviewed_pat_only_vercel_connected_own_organization", "vercel_connectable", False, True, False, False),
+ ("unreviewed_pat_and_passkey_not_provisioned", None, False, True, True, False),
+ ("reviewed_pat_only", "organization", True, True, False, False),
+ ("reviewed_passkey_only", "organization", True, False, True, False),
+ ("reviewed_pat_and_passkey", "organization", True, True, True, False),
+ ("reviewed_nothing", "organization", True, False, False, False),
]
)
def test_requires_credential_review(
self,
_name: str,
+ provisioned_by: ProvisionedBy | None,
reviewed: bool,
with_key: bool,
with_passkey: bool,
expected: bool,
):
+ self._provision_organization(provisioned_by)
self.user.credentials_reviewed_at = timezone.now() if reviewed else None
self.user.save(update_fields=["credentials_reviewed_at"])
if with_key:
@@ -351,6 +378,7 @@ class TestUserAPI(APIBaseTest):
assert response.json()["requires_credential_review"] is expected
def test_requires_credential_review_skipped_when_impersonating_via_session(self):
+ self._provision_organization()
User.objects.filter(pk=self.user.pk).update(credentials_reviewed_at=None)
PersonalAPIKey.objects.create(
user=self.user,
@@ -364,6 +392,7 @@ class TestUserAPI(APIBaseTest):
assert response.json()["requires_credential_review"] is False
def test_requires_credential_review_skipped_when_impersonating_via_oauth_token(self):
+ self._provision_organization()
User.objects.filter(pk=self.user.pk).update(credentials_reviewed_at=None)
PersonalAPIKey.objects.create(
user=self.user,
@@ -399,6 +428,7 @@ class TestUserAPI(APIBaseTest):
def test_requires_credential_review_unverified_passkey(self):
# Unverified passkeys are the realistic pre-claim attack artifact - a partner
# session can register a credential without ever completing verification.
+ self._provision_organization()
self.user.credentials_reviewed_at = None
self.user.save(update_fields=["credentials_reviewed_at"])
WebauthnCredential.objects.create(
@@ -416,21 +446,26 @@ class TestUserAPI(APIBaseTest):
@parameterized.expand(
[
- ("live_access_token", 1, False, False, True),
- ("live_refresh_token_only", -1, True, False, True),
- ("expired_access_token_only", -1, False, False, False),
- ("live_access_token_first_party", 1, False, True, False),
- ("live_refresh_token_only_first_party", -1, True, True, False),
+ ("live_access_token", True, 1, False, False, True),
+ ("live_refresh_token_only", True, -1, True, False, True),
+ ("expired_access_token_only", True, -1, False, False, False),
+ ("live_access_token_first_party", True, 1, False, True, False),
+ ("live_refresh_token_only_first_party", True, -1, True, True, False),
+ ("live_access_token_not_provisioned", False, 1, False, False, False),
+ ("live_refresh_token_only_not_provisioned", False, -1, True, False, False),
]
)
def test_requires_credential_review_for_oauth_access(
self,
_name: str,
+ provisioned: bool,
expires_hours: int,
with_refresh_token: bool,
is_first_party: bool,
expected: bool,
):
+ if provisioned:
+ self._provision_organization()
User.objects.filter(pk=self.user.pk).update(credentials_reviewed_at=None)
app = OAuthApplication.objects.create(
name="Provisioning partner",
@@ -463,6 +498,7 @@ class TestUserAPI(APIBaseTest):
assert response.json()["requires_credential_review"] is expected
def test_credentials_review_complete_endpoint(self):
+ self._provision_organization()
User.objects.filter(pk=self.user.pk).update(credentials_reviewed_at=None)
PersonalAPIKey.objects.create(
user=self.user,
diff --git a/posthog/api/user.py b/posthog/api/user.py
index 00732ff96092..553eac7b20ff 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -16,6 +16,7 @@ from django.contrib.auth.password_validation import validate_password
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
+from django.db.models import Exists, OuterRef
from django.http import HttpResponse, JsonResponse
from django.shortcuts import redirect
from django.utils import timezone as django_timezone
@@ -115,8 +116,11 @@ from posthog.models.oauth import OAuthGrant, find_oauth_refresh_token, has_live_
from posthog.models.onboarding_delegation import cancel_pending_delegation, clear_delegation_state
from posthog.models.organization import Organization, OrganizationMembership
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.team.team_provisioning_config import TeamProvisioningConfig
from posthog.models.user import (
ROLE_CHOICES,
Notifications,
@@ -334,9 +338,10 @@ class UserSerializer(serializers.ModelSerializer):
)
requires_credential_review = serializers.SerializerMethodField(
help_text=(
- "True if the user has at least one Personal API Key or passkey, or a third-party OAuth "
- "application that can currently act as them, and has not yet acknowledged that access. "
- "Used to gate a one-shot review screen on first post-provisioning login. Becomes False "
+ "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."
),
)
@@ -544,6 +549,26 @@ class UserSerializer(serializers.ModelSerializer):
# impersonating users shouldn't bounced into the credential review screen
if is_impersonated(self.context.get("request")):
return False
+ # A self-signed-up user verifies their email before the first login, so nobody else can add
+ # credentials to the account first. TeamProvisioningConfig and a Vercel installation cover
+ # organizations provisioned before OrganizationProvisioning existed. A "connectable" Vercel
+ # integration links an organization the user already owned, so it does not count.
+ organization_id = OuterRef("organization_id")
+ if (
+ not OrganizationMembership.objects.filter(user=instance)
+ .filter(
+ Exists(OrganizationProvisioning.objects.filter(organization_id=organization_id))
+ | Exists(TeamProvisioningConfig.objects.filter(team__organization_id=organization_id))
+ | Exists(
+ OrganizationIntegration.objects.filter(
+ organization_id=organization_id,
+ kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,
+ ).exclude(config__contains={"type": "connectable"})
+ )
+ )
+ .exists()
+ ):
+ return False
if PersonalAPIKey.objects.filter(user=instance).exists():
return True
if WebauthnCredential.objects.filter(user=instance).exists():
@@ -1078,8 +1103,9 @@ class UserViewSet(
"scene_personalisation",
"product_intro_seen",
]
- # Skipping onboarding only hides the onboarding redirect, so an older session may do it.
- time_sensitive_allow_actions = ["hedgehog_config", "onboarding_skip"]
+ # These actions only dismiss a screen (the credential review, the onboarding redirect). Requiring a
+ # fresh session for them sends a user with an older session back to that screen on every load.
+ time_sensitive_allow_actions = ["hedgehog_config", "credentials_review_complete", "onboarding_skip"]
filter_backends = [DjangoFilterBackend]
filterset_fields = ["is_staff", "email"]
queryset = User.objects.filter(is_active=True).order_by("id")
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index 0c178c3f6802..3a77c6a518aa 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -18919,7 +18919,7 @@ export namespace Schemas {
active_realtime_notification_types: Array<string>;
pending_invites: Array<PendingInvite>;
/**
- * True if the user has at least one Personal API Key or passkey, or a third-party OAuth application that can currently act as them, and has not yet acknowledged that access. 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.
+ * 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;
};
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 708e00280a6a..d134c9a19bf8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -78229,7 +78229,7 @@ export namespace Schemas {
/** Real-time notification types that currently have a live dispatch site. Drives the in-app notifications settings UI. Read-only. */
readonly active_realtime_notification_types: readonly string[];
readonly pending_invites: readonly PendingInvite[];
- /** True if the user has at least one Personal API Key or passkey, or a third-party OAuth application that can currently act as them, and has not yet acknowledged that access. 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. */
+ /** 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;
}
@@ -88622,7 +88622,7 @@ export namespace Schemas {
/** Real-time notification types that currently have a live dispatch site. Drives the in-app notifications settings UI. Read-only. */
readonly active_realtime_notification_types?: readonly string[];
readonly pending_invites?: readonly PendingInvite[];
- /** True if the user has at least one Personal API Key or passkey, or a third-party OAuth application that can currently act as them, and has not yet acknowledged that access. 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. */
+ /** 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;
}