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: RLS checks for Postgres (#61326)

Luke Beltoned58f26b9f12
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 813c667e4480..01e318a56a38 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -6016,6 +6016,12 @@ export interface ExternalDataSourceSyncSchema {
* available. The UI should disable selection and surface this string when set.
*/
permission_error?: string | null
+ /**
+ * Advisory warning when row-level security is active for the sync role on this table:
+ * the sync may read fewer rows than the table contains, and the gap can't be measured.
+ * `null`/undefined = no warning. Unlike `permission_error` this does NOT block selection.
+ */
+ rls_warning?: string | null
/**
* User-selected source columns to sync. `null`/undefined = sync all columns.
* PK columns and the active incremental field are always retained server-side.
diff --git a/posthog/temporal/data_imports/sources/common/schema.py b/posthog/temporal/data_imports/sources/common/schema.py
index 310ea7b955bc..59aa9d17cf73 100644
--- a/posthog/temporal/data_imports/sources/common/schema.py
+++ b/posthog/temporal/data_imports/sources/common/schema.py
@@ -24,3 +24,4 @@ class SourceSchema:
should_sync_default: bool = True
label: str | None = None
detected_primary_keys: list[str] | None = None
+ rls_warning: str | None = None
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.py
index 43c2050ba829..28d111e3c9b0 100644
--- a/posthog/temporal/data_imports/sources/postgres/postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py
@@ -511,6 +511,65 @@ def _row_counts_from_conn(
return {}
+def _rls_active_from_conn(
+ connection: psycopg.Connection,
+ schema: str | None,
+ names: list[str] | None,
+) -> dict[str, bool]:
+ """Per-table map of whether row-level security is active for the connecting role.
+
+ Runs even with no schema/names selected: `row_security_active` is a cheap catalog lookup, so
+ there's no cost reason to skip it on the full-table-list view — and that view (the source setup
+ picker) is exactly where the warning needs to show.
+
+ One set-based catalog query rather than a per-table function call, so an odd relation (a view, a
+ foreign table, one dropped mid-discovery) is simply absent from the result instead of erroring
+ the whole batch and dropping every table's warning. Returns only the tables it could resolve;
+ callers treat a missing key as "no warning".
+ """
+ try:
+ with connection.cursor() as cursor:
+ cursor.execute(
+ sql.SQL("SET LOCAL statement_timeout = {timeout}").format(
+ timeout=sql.Literal(1000 * 30) # 30 secs
+ )
+ )
+ discovered_tables, _qualify_with_schema = _get_discovered_tables(cursor, schema, names)
+ if not discovered_tables:
+ return {}
+
+ # (source schema, source table) -> the display name used as the schema key elsewhere.
+ display_by_source = {
+ (schema_name, table_name): display_name
+ for display_name, (_source_catalog, schema_name, table_name) in discovered_tables.items()
+ }
+ wanted = sql.SQL(", ").join(
+ sql.SQL("({}, {})").format(sql.Literal(schema_name), sql.Literal(table_name))
+ for schema_name, table_name in display_by_source
+ )
+ # relkind r/p only: RLS is meaningless on views/foreign tables, and row_security_active
+ # is never called on them so a discovered view can't error the query.
+ query = sql.SQL("""
+ SELECT n.nspname, c.relname, row_security_active(c.oid)
+ FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ JOIN (VALUES {wanted}) AS want(schema_name, table_name)
+ ON n.nspname::text = want.schema_name AND c.relname::text = want.table_name
+ WHERE c.relkind IN ('r', 'p')
+ """).format(wanted=wanted)
+
+ cursor.execute(query)
+ result: dict[str, bool] = {}
+ for nspname, relname, rls_active in cursor.fetchall():
+ display_name = display_by_source.get((nspname, relname))
+ if display_name is not None:
+ result[display_name] = bool(rls_active)
+ return result
+ except Exception as e:
+ capture_exception(e)
+ return {}
+
+
def get_postgres_row_count(
host: str,
port: int,
@@ -1175,6 +1234,25 @@ def _get_table_chunk_size(cursor: psycopg.Cursor, inner_query: sql.Composed, log
return DEFAULT_CHUNK_SIZE
+def _role_subject_to_rls(cursor: psycopg.Cursor, schema: str, table_name: str, logger: FilteringBoundLogger) -> bool:
+ """Whether row-level security is active for the connecting role on this table."""
+ try:
+ query = sql.SQL("""
+ SELECT row_security_active(c.oid)
+ FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = {schema} AND c.relname = {table}
+ """).format(schema=sql.Literal(schema), table=sql.Literal(table_name))
+ cursor.execute(query)
+ row = cursor.fetchone()
+ return bool(row and row[0])
+ except psycopg.errors.QueryCanceled:
+ raise
+ except Exception as e:
+ logger.debug(f"_role_subject_to_rls: Error: {e}", exc_info=e)
+ return False
+
+
def _get_rows_to_sync(cursor: psycopg.Cursor, count_query: sql.Composed, logger: FilteringBoundLogger) -> int:
try:
_explain_query(cursor, count_query, logger)
@@ -1765,6 +1843,14 @@ def postgres_source(
logger.debug(f"Estimated row count failed, falling back to exact count: {e}")
if rows_to_sync is None:
rows_to_sync = _get_rows_to_sync(cursor, count_query, logger)
+
+ if _role_subject_to_rls(cursor, schema, table_name, logger):
+ logger.warning(
+ f"Row-level security is active for the sync role on {schema}.{table_name} "
+ f"(rows visible to this sync: {rows_to_sync}). Grant the role BYPASSRLS "
+ f"or a permissive policy if it should see all rows."
+ )
+
logger.debug("Getting partition settings...")
partition_settings = (
_get_partition_settings(cursor, schema, table_name, logger)
diff --git a/posthog/temporal/data_imports/sources/postgres/source.py b/posthog/temporal/data_imports/sources/postgres/source.py
index 1d2b414cea30..80d7078f6343 100644
--- a/posthog/temporal/data_imports/sources/postgres/source.py
+++ b/posthog/temporal/data_imports/sources/postgres/source.py
@@ -31,6 +31,7 @@ from posthog.temporal.data_imports.sources.postgres.cdc.slot_manager import cdc_
from posthog.temporal.data_imports.sources.postgres.postgres import (
PostgresImplementation,
SSLRequiredError,
+ _rls_active_from_conn,
filter_postgres_incremental_fields,
get_connection_metadata as get_postgres_connection_metadata,
get_foreign_keys as get_postgres_foreign_keys,
@@ -60,6 +61,12 @@ PostgresErrors = {
_POSTGRES_IMPLEMENTATION = PostgresImplementation()
+RLS_WARNING_MESSAGE = (
+ "Row-level security is active on this table for the sync role, so PostHog can only read "
+ "rows the policy permits, and cannot detect how many rows are hidden. "
+ "Granting the sync role BYPASSRLS will silence the check."
+)
+
@SourceRegistry.register
class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDatabaseHostMixin):
@@ -294,6 +301,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
# indexes — that's how we tell "no indexes" apart from "couldn't check".
indexed_columns_by_table: dict[str, set[str]] | None = {}
tables_with_pks: set[str] = set()
+ rls_active_by_table: dict[str, bool] = {}
try:
with pg_connection(
@@ -353,12 +361,16 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
"Failed to detect leading index columns for Postgres schemas", exc_info=e
)
indexed_columns_by_table = None
+
+ # Row-level security check powers the advisory warning in the table picker.
+ rls_active_by_table = _rls_active_from_conn(conn, config.schema, names)
except Exception as e:
# Connection-level failure: neither lookup is usable.
capture_exception(e)
pk_columns_by_table = {}
indexed_columns_by_table = None
tables_with_pks = set()
+ rls_active_by_table = {}
for table_name, discovered_schema in db_schemas.items():
incremental_field_tuples = filter_postgres_incremental_fields(discovered_schema.columns)
@@ -394,6 +406,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
pk_columns_by_table.get(table_name),
discovered_schema.columns,
),
+ rls_warning=RLS_WARNING_MESSAGE if rls_active_by_table.get(table_name) else None,
)
)
diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
index 9b55dd24d6d2..f2177919f297 100644
--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
@@ -56,6 +56,8 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (
_is_partitioned_table,
_is_read_replica,
_normalize_function_names,
+ _rls_active_from_conn,
+ _role_subject_to_rls,
filter_postgres_incremental_fields,
get_foreign_keys,
get_leading_index_columns,
@@ -2608,3 +2610,54 @@ class TestIteratePartitionsRealDb:
)
)
assert sum(t.num_rows for t in tables) == 80
+
+
+class TestRlsDetectionRealDb:
+ def _create_table(self, cursor, *, rls_active: bool) -> None:
+ cursor.execute("CREATE TABLE test_rls_param (id SERIAL PRIMARY KEY, user_id INTEGER)")
+ if not rls_active:
+ return
+ cursor.execute("ALTER TABLE test_rls_param ENABLE ROW LEVEL SECURITY")
+ cursor.execute("ALTER TABLE test_rls_param FORCE ROW LEVEL SECURITY")
+ cursor.execute("CREATE POLICY test_rls_param_policy ON test_rls_param USING (false)")
+ # FORCE subjects a non-superuser owner directly; a superuser bypasses even FORCE, so observe
+ # via a freshly created unprivileged role (a superuser can always create one).
+ cursor.execute("SELECT rolsuper FROM pg_roles WHERE rolname = current_user")
+ if cursor.fetchone()[0]:
+ cursor.execute("CREATE ROLE test_rls_param_role NOLOGIN")
+ cursor.execute("GRANT SELECT ON test_rls_param TO test_rls_param_role")
+ cursor.execute("SET LOCAL ROLE test_rls_param_role")
+
+ @pytest.mark.parametrize("rls_active,expected", [(False, False), (True, True)])
+ @pytest.mark.django_db
+ def test_role_subject_to_rls(self, rls_active, expected):
+ logger = structlog.get_logger()
+ with django_connection.cursor() as dj_cursor:
+ self._create_table(dj_cursor, rls_active=rls_active)
+ try:
+ assert _role_subject_to_rls(cast(Any, dj_cursor), "public", "test_rls_param", logger) is expected
+ finally:
+ dj_cursor.execute("RESET ROLE")
+
+ @pytest.mark.parametrize("rls_active,expected", [(False, False), (True, True)])
+ @pytest.mark.django_db
+ def test_rls_active_from_conn(self, rls_active, expected):
+ with django_connection.cursor() as dj_cursor:
+ self._create_table(dj_cursor, rls_active=rls_active)
+ try:
+ result = _rls_active_from_conn(
+ cast(Any, _DjangoBackedConnection(dj_cursor)), "public", ["test_rls_param"]
+ )
+ assert result == {"test_rls_param": expected}
+ finally:
+ dj_cursor.execute("RESET ROLE")
+
+ @pytest.mark.django_db
+ def test_rls_active_from_conn_runs_without_schema_or_names(self):
+ # Regression: an early-return guard used to bail when no schema and no names were given,
+ # silently dropping every RLS warning in multi-schema discovery. The full table list must
+ # still be checked, so the table appears in the result (keyed by its qualified name).
+ with django_connection.cursor() as dj_cursor:
+ dj_cursor.execute("CREATE TABLE test_rls_noschema (id SERIAL PRIMARY KEY)")
+ result = _rls_active_from_conn(cast(Any, _DjangoBackedConnection(dj_cursor)), "", None)
+ assert "public.test_rls_noschema" in result
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.py
index 4f2752bb8537..afcae7b20211 100644
--- a/products/data_warehouse/backend/api/external_data_source.py
+++ b/products/data_warehouse/backend/api/external_data_source.py
@@ -1910,6 +1910,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
],
"detected_primary_keys": schema.detected_primary_keys,
"permission_error": endpoint_permissions.get(schema.name),
+ "rls_warning": schema.rls_warning,
}
for schema in schemas
]
diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.py
index c01a532bcc76..effc9d4950e1 100644
--- a/products/data_warehouse/backend/api/test/test_external_data_source.py
+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py
@@ -3381,6 +3381,7 @@ class TestExternalDataSource(APIBaseTest):
],
"detected_primary_keys": ["id"],
"permission_error": None,
+ "rls_warning": None,
}
]
@@ -3450,6 +3451,7 @@ class TestExternalDataSource(APIBaseTest):
],
"detected_primary_keys": ["id"],
"permission_error": None,
+ "rls_warning": None,
}
]
diff --git a/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
index eede8766aa85..281a13d070b1 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
@@ -157,6 +157,14 @@ export default function SchemaForm(): JSX.Element {
</LemonTag>
</Tooltip>
)}
+ {schema.rls_warning && (
+ <Tooltip title={schema.rls_warning} placement="top">
+ <LemonTag type="warning" className="cursor-help">
+ <IconWarning className="mr-1" />
+ RLS may hide rows
+ </LemonTag>
+ </Tooltip>
+ )}
</div>
)
},