: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
fix(activity): allow impersonators to bypass audit_logs paywall (#57922)
Yasen10461cf43960
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/SidePanelActivity.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/SidePanelActivity.tsxindex 91736a460434..376a2abda938 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/SidePanelActivity.tsx+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/SidePanelActivity.tsx@@ -15,6 +15,7 @@ import { IconWithCount } from 'lib/lemon-ui/icons'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { userHasAccess } from 'lib/utils/accessControlUtils'import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'import {SidePanelActivityTab,@@ -52,6 +53,7 @@ export const SidePanelActivity = (): JSX.Element => {const { closeSidePanel } = useActions(sidePanelStateLogic)+ const { user } = useValues(userLogic)const { featureFlags } = useValues(featureFlagLogic)const hasAccess = userHasAccess(AccessControlResourceType.ActivityLog, AccessControlLevel.Viewer)@@ -99,7 +101,7 @@ export const SidePanelActivity = (): JSX.Element => {<PayGateMinifeature={AvailableFeature.AUDIT_LOGS}className="flex flex-col flex-1 overflow-hidden"- overrideShouldShowGate={!!featureFlags[FEATURE_FLAGS.AUDIT_LOGS_ACCESS]}+ overrideShouldShowGate={user?.is_impersonated || !!featureFlags[FEATURE_FLAGS.AUDIT_LOGS_ACCESS]}><div className="flex flex-col flex-1 overflow-hidden"><div className="mx-2 shrink-0">diff --git a/frontend/src/lib/components/ActivityLog/ActivityLog.tsx b/frontend/src/lib/components/ActivityLog/ActivityLog.tsxindex c72a76f254d8..cf42d67dddbd 100644--- a/frontend/src/lib/components/ActivityLog/ActivityLog.tsx+++ b/frontend/src/lib/components/ActivityLog/ActivityLog.tsx@@ -21,6 +21,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { userHasAccess } from 'lib/utils/accessControlUtils'import { copyToClipboard } from 'lib/utils/copyToClipboard'import { billingLogic } from 'scenes/billing/billingLogic'+import { userLogic } from 'scenes/userLogic'import { ProductKey } from '~/queries/schema/schema-general'import { AccessControlLevel, AccessControlResourceType, AvailableFeature } from '~/types'@@ -259,6 +260,7 @@ export const ActivityLogRow = ({export const ActivityLog = ({ scope, id, caption, startingPage = 1 }: ActivityLogProps): JSX.Element | null => {const logic = activityLogLogic({ scope, id, caption, startingPage })const { humanizedActivity, activityLoading, pagination, highlightedActivityId } = useValues(logic)+ const { user } = useValues(userLogic)const { featureFlags } = useValues(featureFlagLogic)const { billingLoading } = useValues(billingLogic)@@ -278,7 +280,7 @@ export const ActivityLog = ({ scope, id, caption, startingPage = 1 }: ActivityLo) : (<PayGateMinifeature={AvailableFeature.AUDIT_LOGS}- overrideShouldShowGate={!!featureFlags[FEATURE_FLAGS.AUDIT_LOGS_ACCESS]}+ overrideShouldShowGate={user?.is_impersonated || !!featureFlags[FEATURE_FLAGS.AUDIT_LOGS_ACCESS]}>{humanizedActivity.length === 0 ? (<Empty scope={scope} />diff --git a/frontend/src/scenes/audit-logs/AdvancedActivityLogsScene.tsx b/frontend/src/scenes/audit-logs/AdvancedActivityLogsScene.tsxindex 373e7e739a07..a57404966ff7 100644--- a/frontend/src/scenes/audit-logs/AdvancedActivityLogsScene.tsx+++ b/frontend/src/scenes/audit-logs/AdvancedActivityLogsScene.tsx@@ -9,6 +9,7 @@ import { userHasAccess } from 'lib/utils/accessControlUtils'import { SceneExport } from 'scenes/sceneTypes'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'@@ -28,6 +29,7 @@ export function AdvancedActivityLogsScene(): JSX.Element | null {const { activeTab } = useValues(advancedActivityLogsLogic)const { setActiveTab } = useActions(advancedActivityLogsLogic)const { currentTeam } = useValues(teamLogic)+ const { user } = useValues(userLogic)const hasAccess = userHasAccess(AccessControlResourceType.ActivityLog, AccessControlLevel.Viewer)const includesOrgLevelLogs = currentTeam?.receive_org_level_activity_logs@@ -67,7 +69,7 @@ export function AdvancedActivityLogsScene(): JSX.Element | null {forceIcon: <IconNotification />,}}/>- <PayGateMini feature={AvailableFeature.AUDIT_LOGS}>+ <PayGateMini feature={AvailableFeature.AUDIT_LOGS} overrideShouldShowGate={user?.is_impersonated}><LemonTabsactiveKey={activeTab}onChange={(key) => setActiveTab(key as 'logs' | 'exports')}diff --git a/frontend/src/scenes/settings/environment/ActivityLogSettings.tsx b/frontend/src/scenes/settings/environment/ActivityLogSettings.tsxindex 1030020021cb..763dcf5bf7ae 100644--- a/frontend/src/scenes/settings/environment/ActivityLogSettings.tsx+++ b/frontend/src/scenes/settings/environment/ActivityLogSettings.tsx@@ -10,20 +10,23 @@ import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { LinkedHogFunctions } from 'scenes/hog-functions/list/LinkedHogFunctions'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'import { AvailableFeature } from '~/types'export function ActivityLogSettings(): JSX.Element {+ const { user } = useValues(userLogic)const restrictedReason = useRestrictedArea({scope: RestrictionScope.Project,minimumAccessLevel: TeamMembershipLevel.Admin,})+ const effectiveRestriction = user?.is_impersonated ? null : restrictedReasonreturn (- <PayGateMini feature={AvailableFeature.AUDIT_LOGS}>+ <PayGateMini feature={AvailableFeature.AUDIT_LOGS} overrideShouldShowGate={user?.is_impersonated}><div className="flex"><p>- <LemonButton to={urls.advancedActivityLogs()} type="primary" disabledReason={restrictedReason}>+ <LemonButton to={urls.advancedActivityLogs()} type="primary" disabledReason={effectiveRestriction}>Browse all activity logs</LemonButton></p>@@ -33,6 +36,7 @@ export function ActivityLogSettings(): JSX.Element {}export function ActivityLogOrgLevelSettings(): JSX.Element {+ const { user } = useValues(userLogic)const { currentTeam } = useValues(teamLogic)const { updateCurrentTeam } = useActions(teamLogic)const { reportActivityLogSettingToggled } = useActions(eventUsageLogic)@@ -45,7 +49,7 @@ export function ActivityLogOrgLevelSettings(): JSX.Element {}return (- <PayGateMini feature={AvailableFeature.AUDIT_LOGS}>+ <PayGateMini feature={AvailableFeature.AUDIT_LOGS} overrideShouldShowGate={user?.is_impersonated}><div><p className="flex items-center gap-1">Include organization-level activity logs in this project.@@ -76,6 +80,7 @@ export function ActivityLogOrgLevelSettings(): JSX.Element {}export function ActivityLogNotifications(): JSX.Element | null {+ const { user } = useValues(userLogic)const restrictedReason = useRestrictedArea({scope: RestrictionScope.Project,minimumAccessLevel: TeamMembershipLevel.Admin,@@ -86,7 +91,7 @@ export function ActivityLogNotifications(): JSX.Element | null {}return (- <PayGateMini feature={AvailableFeature.AUDIT_LOGS}>+ <PayGateMini feature={AvailableFeature.AUDIT_LOGS} overrideShouldShowGate={user?.is_impersonated}><div><p className="flex items-center gap-1">Create notifications to get notified of activity logs.diff --git a/posthog/api/test/test_activity_log.py b/posthog/api/test/test_activity_log.pyindex 08c23d7a833f..02c01a834d4a 100644--- a/posthog/api/test/test_activity_log.py+++ b/posthog/api/test/test_activity_log.py@@ -4,6 +4,7 @@ from typing import Any, Optionalfrom freezegun import freeze_timefrom freezegun.api import FrozenDateTimeFactory, StepTickTimeFactory, TickingDateTimeFactoryfrom posthog.test.base import APIBaseTest, QueryMatchingTest+from unittest.mock import patchfrom parameterized import parameterizedfrom rest_framework import status@@ -225,3 +226,13 @@ class TestActivityLogAuditLogsGate(APIBaseTest):res = self.client.get(f"/api/projects/{self.team.id}/{endpoint}/")assert res.status_code == status.HTTP_200_OK++ @parameterized.expand([("activity_log",), ("advanced_activity_logs",)])+ def test_endpoint_allowed_for_impersonator_without_audit_logs_feature(self, endpoint: str) -> None:+ self.organization.available_product_features = []+ self.organization.save()++ with self.is_cloud(True), patch("posthog.permissions.is_impersonated_session", return_value=True):+ res = self.client.get(f"/api/projects/{self.team.id}/{endpoint}/")++ assert res.status_code == status.HTTP_200_OKdiff --git a/posthog/api/test/test_materialized_column_slot.py b/posthog/api/test/test_materialized_column_slot.pyindex b71155286f49..42b59686fbf2 100644--- a/posthog/api/test/test_materialized_column_slot.py+++ b/posthog/api/test/test_materialized_column_slot.py@@ -651,7 +651,7 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):response = self.client.get(endpoint)assert response.status_code == status.HTTP_403_FORBIDDEN- @patch("loginas.utils.is_impersonated_session")+ @patch("posthog.permissions.is_impersonated_session")@patch("posthog.api.materialized_column_slot.async_to_sync")def test_endpoints_allow_impersonated_sessions(self, mock_async_to_sync, mock_is_impersonated):"""Test that impersonated sessions can access endpoints."""diff --git a/posthog/permissions.py b/posthog/permissions.pyindex 8792e78ad2e5..9b363e343f7d 100644--- a/posthog/permissions.py+++ b/posthog/permissions.py@@ -7,6 +7,7 @@ from django.core.exceptions import ImproperlyConfiguredfrom django.db.models import Modelimport posthoganalytics+from loginas.utils import is_impersonated_sessionfrom rest_framework.exceptions import AuthenticationFailed, NotFound, PermissionDeniedfrom rest_framework.permissions import SAFE_METHODS, BasePermission, IsAdminUserfrom rest_framework.request import Request@@ -268,8 +269,6 @@ class IsStaffUserOrImpersonating(BasePermission):message = "You are not a staff user, contact your instance admin."def has_permission(self, request: Request, view: APIView) -> bool:- from loginas.utils import is_impersonated_session-return bool(request.userand request.user.is_authenticated@@ -288,6 +287,11 @@ class PremiumFeaturePermission(BasePermission):Self-hosted instances are not gated.Exactly one of the two attributes must be set on the view.++ Staff impersonating a customer (`is_impersonated_session`) bypass the feature check+ so PostHog support can debug paid features for non-paying orgs. Plain staff sessions+ are not bypassed — staff must actively start an impersonation session, which is+ audit-logged via the `loginas` flow."""def has_permission(self, request: Request, view: APIView) -> bool:@@ -305,6 +309,9 @@ class PremiumFeaturePermission(BasePermission):else:feature = always_feature+ if is_impersonated_session(request):+ return True+try:organization = get_organization_from_view(view)except ValueError: