: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-logs): gate SQL access to activity logs on the audit logs entitlement (#78107)
Yasen6932ec54aaa8
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 1b8975b05487..2bdd5f266db9 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -7,9 +7,10 @@ import threadingimport dataclassesimport pickletoolsfrom collections import defaultdict-from collections.abc import Callable, Sequence+from collections.abc import Callable, Mapping, Sequencefrom datetime import UTC, datetimefrom functools import cache+from types import MappingProxyTypefrom typing import TYPE_CHECKING, Any, Literal, Optional, Union, castfrom zoneinfo import ZoneInfo, ZoneInfoNotFoundError@@ -451,22 +452,60 @@ def _construct_database_root_node(*, include_posthog_tables: bool) -> TableNode:@cache-def _system_table_access_scopes() -> tuple[tuple[str, APIScopeObject], ...]:- """(table name, access scope) for the access-controlled Postgres system tables.+def _system_table_access_scopes() -> Mapping[str, APIScopeObject]:+ """Table name -> access scope for the access-controlled Postgres system tables.Cached for the process lifetime — this result directly gates table visibility in access-controldecisions, so every entry here MUST remain process-static. Do NOT make a system table'saccess_scope dynamic (per-team, per-flag, or env-driven at call time): this cache would silentlyserve stale scopes and bypass the restriction. Today SystemTables().children is a staticclass-level dict of module-level PostgresTable constants, which satisfies that invariant.+ Returned read-only so a caller can't mutate the shared cached mapping."""- return tuple(- (name, table_node.table.access_scope)- for name, table_node in SystemTables().children.items()- if isinstance(table_node.table, PostgresTable) and table_node.table.access_scope is not None+ return MappingProxyType(+ {+ name: table_node.table.access_scope+ for name, table_node in SystemTables().children.items()+ if isinstance(table_node.table, PostgresTable) and table_node.table.access_scope is not None+ }+ )+++@cache+def _system_table_required_features() -> Mapping[str, str]:+ """Table name -> required AvailableFeature for system tables behind a billing entitlement.++ Same process-static invariant as _system_table_access_scopes: the entitlement a table *requires*+ is a static property of the table. What varies per organization is whether that entitlement is+ *available*, which is resolved uncached in _unentitled_system_tables. Returned read-only so a+ caller can't mutate the shared cached mapping.+ """+ return MappingProxyType(+ {+ name: table_node.table.required_feature_on_cloud+ for name, table_node in SystemTables().children.items()+ if isinstance(table_node.table, PostgresTable) and table_node.table.required_feature_on_cloud is not None+ })+def _unentitled_system_tables(team: Team) -> set[str]:+ """System tables the team's organization is not entitled to, hidden from the schema.++ Entitlement is organization-wide, so unlike RBAC this applies to every principal including+ organization admins. Cloud-only, mirroring PremiumFeaturePermission's `premium_feature_on_cloud`.+ """+ # Lazy imports keep the Django ORM off this module's import path.+ from posthog.cloud_utils import is_cloud # noqa: PLC0415++ required_features = _system_table_required_features()+ if not required_features or not is_cloud():+ return set()++ organization = team.organization+ return {name for name, feature in required_features.items() if not organization.is_feature_available(feature)}++def _compute_system_table_access_decision(team: Team,user: Optional[User | SyntheticUser | SharedLinkUser],@@ -483,20 +522,25 @@ def _compute_system_table_access_decision(from posthog.shared_link_user import SharedLinkUser # noqa: PLC0415scoped_tables = _system_table_access_scopes()+ # Applies to every principal below, admins included - an entitlement the organization does not+ # have cannot be granted by a role.+ unentitled = _unentitled_system_tables(team)# Anonymous or synthetic principal: keep only access-controlled tables its scopes cover (none for shared link / team token).if user is None or isinstance(user, SyntheticUser | SharedLinkUser):readable_scopes = user.readable_system_table_access_scopes() if user is not None else set()- return None, {name for name, access_scope in scoped_tables if access_scope not in readable_scopes}+ return None, unentitled | {+ name for name, access_scope in scoped_tables.items() if access_scope not in readable_scopes+ }user_access_control = user_access_control or UserAccessControl(user=user, team=team)org_membership = user_access_control._organization_membershipif org_membership and org_membership.level >= OrganizationMembership.Level.ADMIN:- return user_access_control, set()+ return user_access_control, unentitled- denied: set[str] = set()- for name, access_scope in scoped_tables:+ denied: set[str] = set(unentitled)+ for name, access_scope in scoped_tables.items():access_level = user_access_control.access_level_for_resource(access_scope)if access_level and access_level != NO_ACCESS_LEVEL:continue # User has access, keep itdiff --git a/posthog/hogql/database/postgres_table.py b/posthog/hogql/database/postgres_table.pyindex 172b6497af4a..8a72cc9d38fd 100644--- a/posthog/hogql/database/postgres_table.py+++ b/posthog/hogql/database/postgres_table.py@@ -87,6 +87,10 @@ class PostgresTable(FunctionCallTable):requires_args: bool = Falsepostgres_table_name: straccess_scope: Optional[APIScopeObject] = None+ # Billing entitlement required to query this table, mirroring `premium_feature_on_cloud` on the+ # REST viewsets: enforced on Cloud only, self-hosted stays ungated. Holds an `AvailableFeature`+ # value as a plain string so this module keeps the ORM off its import path.+ required_feature_on_cloud: Optional[str] = None# Column that object-level access control filters ids against.# Defaults to the primary key, which is correct when the table's rows ARE the access-controlled object# (e.g. system.dashboards). Child tables that only expose a parent object's data set thisdiff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.pyindex f38e3e9965a0..0f10fd5d641c 100644--- a/posthog/hogql/database/schema/system.py+++ b/posthog/hogql/database/schema/system.py@@ -29,6 +29,7 @@ from posthog.hogql.database.schema.information_schema import information_schema_from posthog.hogql.errors import ResolutionErrorfrom posthog.hogql.parser import parse_expr, parse_select+from posthog.constants import AvailableFeaturefrom posthog.scopes import APIScopeObjectfrom products.customer_analytics.backend.facade.hogql import (@@ -984,6 +985,8 @@ activity_logs: PostgresTable = PostgresTable(name="activity_logs",postgres_table_name="posthog_activitylog",access_scope="activity_log",+ # Matches `premium_feature_on_cloud` on the REST activity-log viewsets, which gate the same rows.+ required_feature_on_cloud=AvailableFeature.AUDIT_LOGS,description="Audit trail of changes to objects (insights, flags, dashboards, etc.); one row per logged activity.",fields={"id": StringDatabaseField(name="id", description="Activity log entry UUID."),diff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.pyindex c6ab0f58e321..c35824048787 100644--- a/posthog/hogql/database/test/test_database.py+++ b/posthog/hogql/database/test/test_database.py@@ -64,8 +64,9 @@ from posthog.hogql.printer import prepare_and_print_astfrom posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.test.utils import pretty_print_in_tests+from posthog.constants import AvailableFeaturefrom posthog.models.group_type_mapping import invalidate_group_types_cache-from posthog.models.organization import Organization+from posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.team.team import Teamfrom posthog.test.test_utils import create_group_type_mapping_without_created_at@@ -3681,3 +3682,34 @@ class TestDatabase(BaseTest, QueryMatchingTest):user_access_control, _denied = captured["result"]# A real user gets per-user access control computed rather than the anonymous all-deny path.assert user_access_control is not None++ @parameterized.expand(+ [+ # Admin/owner cases matter most: they short-circuit RBAC, so an entitlement check placed+ # only in the per-resource loop would let them keep querying a table the org can't buy.+ ("cloud_unentitled_admin", True, False, OrganizationMembership.Level.ADMIN, False),+ ("cloud_unentitled_owner", True, False, OrganizationMembership.Level.OWNER, False),+ ("cloud_unentitled_member", True, False, OrganizationMembership.Level.MEMBER, False),+ ("cloud_entitled_admin", True, True, OrganizationMembership.Level.ADMIN, True),+ ("self_hosted_unentitled_admin", False, False, OrganizationMembership.Level.ADMIN, True),+ ]+ )+ def test_entitlement_gated_system_table_visibility(+ self,+ _name: str,+ cloud: bool,+ entitled: bool,+ level: "OrganizationMembership.Level",+ expected_visible: bool,+ ):+ self.organization.available_product_features = (+ [{"key": AvailableFeature.AUDIT_LOGS, "name": AvailableFeature.AUDIT_LOGS}] if entitled else []+ )+ self.organization.save()+ self.organization_membership.level = level+ self.organization_membership.save()++ with self.is_cloud(cloud):+ database = Database.create_for(team=self.team, user=self.user)++ assert ("system.activity_logs" in database.get_system_table_names()) is expected_visible