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(hogql): Validate batch export queries as the saved user (#105280)

Tomás Farías Santana37a58a2bbb1a
diff --git a/products/batch_exports/backend/api/batch_export.py b/products/batch_exports/backend/api/batch_export.py
index 9d24aa5d112d..5e4d644eca3c 100644
--- a/products/batch_exports/backend/api/batch_export.py
+++ b/products/batch_exports/backend/api/batch_export.py
@@ -1750,7 +1750,17 @@ class BatchExportSerializer(serializers.ModelSerializer):
_set_default_parquet_extension(destination_data["type"], destination_data["config"])
destination = BatchExportDestination(**destination_data)
- batch_export = BatchExport(team_id=team_id, destination=destination, source=source, **validated_data)
+ user = self.context["request"].user
+ if not isinstance(user, User):
+ raise NotAuthenticated()
+
+ batch_export = BatchExport(
+ team_id=team_id,
+ destination=destination,
+ source=source,
+ last_modified_by=user,
+ **validated_data,
+ )
sync_batch_export(batch_export, created=True)
@@ -1803,9 +1813,6 @@ class BatchExportSerializer(serializers.ModelSerializer):
check_hogql_batch_exports_enabled(team)
source = self.instance.source if self.instance is not None else None
- if source is not None and "hogql_query" not in attrs:
- return
-
hogql_query = attrs.get("hogql_query", source.hogql_query if source is not None else None)
if not hogql_query:
raise serializers.ValidationError({"hogql_query": "'hogql_query' is required when 'model' is 'hogql'"})
@@ -1879,6 +1886,12 @@ class BatchExportSerializer(serializers.ModelSerializer):
hogql_query_provided = "hogql_query" in validated_data
hogql_query = validated_data.pop("hogql_query", None)
+ user = self.context["request"].user
+ if not isinstance(user, User):
+ raise NotAuthenticated()
+
+ validated_data["last_modified_by"] = user
+
with transaction.atomic():
if destination_data:
# Type changes are rejected by `validate_destination` — the incoming `type`
diff --git a/products/batch_exports/backend/api/file_download.py b/products/batch_exports/backend/api/file_download.py
index 3547144d2e3e..735e0235ca0f 100644
--- a/products/batch_exports/backend/api/file_download.py
+++ b/products/batch_exports/backend/api/file_download.py
@@ -16,7 +16,7 @@ from botocore.client import Config
from botocore.exceptions import ClientError
from drf_spectacular.utils import OpenApiResponse, PolymorphicProxySerializer, extend_schema
from rest_framework import mixins, response, serializers, status, viewsets
-from rest_framework.exceptions import APIException, NotFound, ValidationError
+from rest_framework.exceptions import APIException, NotAuthenticated, NotFound, ValidationError
from rest_framework.throttling import BaseThrottle
from posthog.hogql.errors import ExposedHogQLError
@@ -28,7 +28,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.errors import ExposedCHQueryError
from posthog.exceptions import ClickHouseQueryTimeOut
-from posthog.models import Team
+from posthog.models import Team, User
from posthog.rate_limit import BatchExportsCountRowsBurstRateThrottle, BatchExportsCountRowsSustainedRateThrottle
from posthog.temporal.common.client import sync_connect
@@ -248,6 +248,7 @@ def count_rows_for_hogql_batch_export(
hogql_query: str,
timeout: int = 30,
*,
+ user: User,
data_interval_start: dt.datetime | None = None,
data_interval_end: dt.datetime | None = None,
) -> int:
@@ -256,9 +257,9 @@ def count_rows_for_hogql_batch_export(
Raises:
UnsupportedHogQLQueryError: If the query cannot power a batch export.
"""
- validate_hogql_query_for_batch_export(hogql_query, team)
+ validate_hogql_query_for_batch_export(hogql_query, team, user=user)
- record_batch_model = HogQLQueryRecordBatchModel(team_id=team.pk, hogql_query=hogql_query)
+ record_batch_model = HogQLQueryRecordBatchModel(team_id=team.pk, hogql_query=hogql_query, user_id=user.pk)
query_settings = get_user_hogql_batch_export_query_settings()
query_settings.max_execution_time = timeout
@@ -268,6 +269,7 @@ def count_rows_for_hogql_batch_export(
query_response = execute_hogql_query(
query=record_batch_model.get_count_hogql_query(data_interval_start, data_interval_end),
team=team,
+ user=user,
query_type="HogQLBatchExportCountRowsQuery",
settings=query_settings,
)
@@ -352,7 +354,17 @@ class FileDownloadBatchExportOnDemandSerializer(serializers.Serializer):
config["exclude_events"] = exclude
destination = BatchExportDestination(type=BatchExportDestination.Destination.FILE_DOWNLOAD, config=config)
- batch_export = BatchExportOnDemand(team_id=team_id, destination=destination, source=source, **validated_data)
+ user = self.context["request"].user
+ if not isinstance(user, User):
+ raise NotAuthenticated()
+
+ batch_export = BatchExportOnDemand(
+ team_id=team_id,
+ destination=destination,
+ source=source,
+ last_modified_by=user,
+ **validated_data,
+ )
batch_export_run = BatchExportRun(
status=BatchExportRun.Status.STARTING,
batch_export_on_demand=batch_export,
@@ -528,6 +540,9 @@ class FileDownloadBatchExportOnDemandViewSet(
name=instance.batch_export_on_demand.model,
schema=None,
hogql_query=source.hogql_query if source is not None else None,
+ user_id=instance.batch_export_on_demand.last_modified_by_id
+ if instance.batch_export_on_demand.model == "hogql"
+ else None,
),
compression=instance.batch_export_on_demand.destination.config.get("compression", None),
format=instance.batch_export_on_demand.destination.config.get("format", "Parquet"),
@@ -704,12 +719,15 @@ class FileDownloadBatchExportOnDemandViewSet(
@validated_request(request_serializer=FileDownloadCountRowsRequestSerializer)
def count_rows(self, request: ValidatedRequest, *args, **kwargs) -> response.Response:
"""Count the rows a HogQL batch export would produce if started now."""
+ if not isinstance(request.user, User):
+ raise NotAuthenticated()
check_hogql_batch_exports_enabled(self.team)
try:
count = count_rows_for_hogql_batch_export(
self.team,
request.validated_data["hogql_query"],
+ user=request.user,
data_interval_start=request.validated_data.get("data_interval_start"),
data_interval_end=request.validated_data.get("data_interval_end"),
)
diff --git a/products/batch_exports/backend/hogql_source.py b/products/batch_exports/backend/hogql_source.py
index f165ea4bb3ba..b7885340a361 100644
--- a/products/batch_exports/backend/hogql_source.py
+++ b/products/batch_exports/backend/hogql_source.py
@@ -115,6 +115,21 @@ def replace_interval_placeholders(
)
+def validate_hogql_batch_export_user(team: "Team", user: "User | None") -> None:
+ from posthog.models import User # noqa: PLC0415 - keeps Django models off the worker import path
+ from posthog.user_permissions import UserPermissions # noqa: PLC0415 - requires initialized Django models
+
+ if not isinstance(user, User) or not user.is_active:
+ raise UnsupportedHogQLQueryError(
+ "This HogQL export needs an active user. Save the export again with a user who has access to this project."
+ )
+ if UserPermissions(user=user, team=team).current_team.effective_membership_level is None:
+ raise UnsupportedHogQLQueryError(
+ "The user who saved this HogQL export no longer has access to this project. "
+ "Save the export again with a user who has access."
+ )
+
+
def create_hogql_context_for_batch_export(
team: "Team", values: dict[str, typing.Any] | None = None, user: "User | None" = None
) -> HogQLContext:
@@ -137,7 +152,7 @@ def create_hogql_context_for_batch_export(
values=values if values is not None else {},
modifiers=create_default_modifiers_for_team(team),
)
- context.database = Database.create_for(team=team, modifiers=context.modifiers)
+ context.database = Database.create_for(team=team, user=user, modifiers=context.modifiers)
return context
@@ -161,11 +176,11 @@ def _validate_select_columns_are_named(parsed: ast.SelectQuery | ast.SelectSetQu
)
-def validate_hogql_query_for_batch_export(hogql_query: str, team: "Team", user: "User | None" = None) -> None:
+def validate_hogql_query_for_batch_export(hogql_query: str, team: "Team", *, user: "User") -> None:
"""Validate a HogQL query can power a batch export for the given team.
- Parses the query, checks output columns are named, and resolves types against the
- team's database (catching unknown tables/fields) with the same context the worker
+ Parses the query, checks output columns are named, and compiles it with the user's
+ table and property permissions using the same context the worker
will execute with. Resolution runs on the query with any interval placeholders
substituted, exactly as a run does, so misuse that breaks resolution is caught
here instead of failing every run. A query without placeholders is equally valid:
@@ -175,6 +190,7 @@ def validate_hogql_query_for_batch_export(hogql_query: str, team: "Team", user:
UnsupportedHogQLQueryError: If the query cannot power a batch export.
InternalHogQLError: Left to propagate, as in `parse_hogql_select_for_batch_export`.
"""
+ validate_hogql_batch_export_user(team, user)
parsed = parse_hogql_select_for_batch_export(hogql_query)
_validate_select_columns_are_named(parsed)
@@ -182,7 +198,9 @@ def validate_hogql_query_for_batch_export(hogql_query: str, team: "Team", user:
context = create_hogql_context_for_batch_export(team, user=user)
try:
- prepare_ast_for_printing(parsed, context=context, dialect="clickhouse", stack=[])
+ prepared = prepare_ast_for_printing(parsed, context=context, dialect="clickhouse", stack=[])
+ assert prepared is not None
+ print_prepared_ast(prepared, context=context, dialect="clickhouse", stack=[])
except ExposedHogQLError as e:
raise UnsupportedHogQLQueryError(f"Invalid HogQL query: {e}") from e
diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.py
index 319ac34bf07b..8c172c082b5c 100644
--- a/products/batch_exports/backend/service.py
+++ b/products/batch_exports/backend/service.py
@@ -153,12 +153,14 @@ class BatchExportEventPropertyFilter:
SUPPORTED_FILTER_TYPES = {"event", "person", "hogql"}
-@dataclass
+@dataclass(frozen=False)
class BatchExportModel:
name: str
schema: BatchExportSchema | None
filters: list[dict[str, str | list[str] | None]] | None = None
hogql_query: str | None = None
+ # The user who last modified the batch export. This is used for validating custom HogQL queries. This is stored alongside the query, not looked up at runtime, so that an edit during a run cannot pair the old query with a new user.
+ user_id: int | None = None
@dataclass
@@ -1210,6 +1212,9 @@ def sync_batch_export(batch_export: BatchExport, created: bool):
schema=batch_export.schema,
filters=batch_export.filters,
hogql_query=batch_export.hogql_query,
+ user_id=batch_export.last_modified_by_id
+ if batch_export.model == BatchExport.Model.HOGQL
+ else None,
),
# TODO: This field is deprecated, but we still set it for backwards compatibility.
# New exports created will always have `batch_export_schema` set to `None`, but existing
diff --git a/products/batch_exports/backend/temporal/record_batch_model.py b/products/batch_exports/backend/temporal/record_batch_model.py
index 1f2f39ab57b2..948b2cd8e3c1 100644
--- a/products/batch_exports/backend/temporal/record_batch_model.py
+++ b/products/batch_exports/backend/temporal/record_batch_model.py
@@ -7,6 +7,7 @@ from posthog.schema import HogQLQueryModifiers, MaterializationMode, PersonsOnEv
from posthog.hogql.constants import HogQLQuerySettings
from posthog.hogql.context import HogQLContext
+from posthog.hogql.errors import ExposedHogQLError
from posthog.hogql.hogql import ast
from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.printer import prepare_ast_for_printing, print_prepared_ast
@@ -15,7 +16,7 @@ from posthog.hogql.visitor import clone_expr
from posthog.clickhouse import query_tagging
from posthog.clickhouse.query_tagging import Product
from posthog.credentials import AWSKeyPair
-from posthog.models import Team
+from posthog.models import Team, User
from posthog.models.event.new_events_schema import use_new_events_schema
from posthog.sync import database_sync_to_async
from posthog.temporal.common.clickhouse import get_client
@@ -29,6 +30,7 @@ from products.batch_exports.backend.hogql_source import (
parse_hogql_select_for_batch_export,
replace_interval_placeholders,
serialize_batch_export_query,
+ validate_hogql_batch_export_user,
)
from products.batch_exports.backend.service import BatchExportModel, BatchExportSchema
from products.batch_exports.backend.temporal.errors import MissingRequiredInputsError
@@ -369,14 +371,33 @@ class HogQLQueryRecordBatchModel(RecordBatchModel):
placeholders run unchanged.
"""
- def __init__(self, team_id: int, hogql_query: str, batch_export_id: str | None = None):
+ def __init__(
+ self, team_id: int, hogql_query: str, batch_export_id: str | None = None, user_id: int | None = None
+ ) -> None:
super().__init__(team_id=team_id, batch_export_id=batch_export_id)
+ self.user_id = user_id
self.hogql_query = hogql_query
self.parsed_hogql_query = parse_hogql_select_for_batch_export(hogql_query)
self.wait_for_data_interval_end = DATA_INTERVAL_END_PLACEHOLDER in find_interval_placeholders(
self.parsed_hogql_query
)
+ async def get_hogql_context(self) -> HogQLContext:
+ team = await Team.objects.aget(id=self.team_id)
+ user = await User.objects.filter(pk=self.user_id).afirst()
+ await database_sync_to_async(validate_hogql_batch_export_user)(team, user)
+ return await database_sync_to_async(create_hogql_context_for_batch_export)(
+ team, user=user, values={"log_comment": self.get_log_comment()}
+ )
+
+ async def _print_query(
+ self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime | None, output_format: str | None
+ ) -> tuple[str, QueryParameters]:
+ try:
+ return await super()._print_query(data_interval_start, data_interval_end, output_format)
+ except ExposedHogQLError as e:
+ raise UnsupportedHogQLQueryError(f"Invalid HogQL query: {e}") from e
+
def get_hogql_query(
self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime | None
) -> ast.SelectQuery | ast.SelectSetQuery:
@@ -430,7 +451,10 @@ def resolve_batch_exports_model(
if model.hogql_query is None:
raise UnsupportedHogQLQueryError("Batch export model is 'hogql' but no HogQL query was provided")
record_batch_model = HogQLQueryRecordBatchModel(
- team_id=team_id, hogql_query=model.hogql_query, batch_export_id=batch_export_id
+ team_id=team_id,
+ hogql_query=model.hogql_query,
+ batch_export_id=batch_export_id,
+ user_id=model.user_id,
)
else:
model_name = "events"
diff --git a/products/batch_exports/backend/tests/api/test_create.py b/products/batch_exports/backend/tests/api/test_create.py
index 971154ac799a..b5d394237c62 100644
--- a/products/batch_exports/backend/tests/api/test_create.py
+++ b/products/batch_exports/backend/tests/api/test_create.py
@@ -13,8 +13,11 @@ from rest_framework import status
from posthog.api.test.test_team import create_team
from posthog.api.test.test_user import create_user
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership
from posthog.models.integration import Integration
+from products.access_control.backend.models.access_control import AccessControl
from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportSource
from products.batch_exports.backend.tests.api.conftest import (
assert_is_daily_schedule,
@@ -23,6 +26,7 @@ from products.batch_exports.backend.tests.api.conftest import (
)
from products.batch_exports.backend.tests.api.fixtures import create_organization
from products.batch_exports.backend.tests.api.operations import create_batch_export, list_batch_exports_ok
+from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable
pytestmark = [
pytest.mark.django_db,
@@ -46,6 +50,7 @@ def test_create_batch_export_with_interval_schedule(
"""
interval = "hour"
+ other_user = create_user("[email protected]", "Test User", organization)
destination_data = {
"type": "S3Compatible",
@@ -63,6 +68,7 @@ def test_create_batch_export_with_interval_schedule(
"name": "my-production-s3-bucket-destination",
"destination": destination_data,
"interval": interval,
+ "last_modified_by": other_user.pk,
}
client.force_login(user)
@@ -89,6 +95,7 @@ def test_create_batch_export_with_interval_schedule(
schedule = describe_schedule(temporal, data["id"])
batch_export = BatchExport.objects.get(id=data["id"])
+ assert batch_export.last_modified_by_id == user.pk
assert schedule.schedule.spec.intervals[0].every == batch_export.interval_time_delta
assert schedule.schedule.spec.jitter == batch_export.jitter
@@ -99,6 +106,7 @@ def test_create_batch_export_with_interval_schedule(
assert args["team_id"] == team.pk
assert args["batch_export_id"] == data["id"]
assert args["interval"] == interval
+ assert args["batch_export_model"]["user_id"] is None
# expected jitter is 15 minutes for hourly exports
assert batch_export.jitter == dt.timedelta(minutes=15)
@@ -519,6 +527,7 @@ def test_create_batch_export_with_custom_schema(
"name": "events",
"schema": expected_schema,
"hogql_query": None,
+ "user_id": None,
}
@@ -592,8 +601,11 @@ def test_create_batch_export_with_hogql_model(
client: HttpClient, temporal, encryption_codec, organization, team, user, hogql_batch_export_data
):
client.force_login(user)
+ other_user = create_user("[email protected]", "Test User", organization)
- response = create_batch_export(client, team.pk, hogql_batch_export_data)
+ response = create_batch_export(
+ client, team.pk, {**hogql_batch_export_data, "last_modified_by": other_user.pk, "user_id": other_user.pk}
+ )
assert response.status_code == status.HTTP_201_CREATED, response.json()
data = response.json()
@@ -602,6 +614,7 @@ def test_create_batch_export_with_hogql_model(
assert data["schema"] is None
batch_export = BatchExport.objects.select_related("source").get(id=data["id"])
+ assert batch_export.last_modified_by_id == user.pk
assert batch_export.source is not None
assert batch_export.source.team_id == team.pk
assert batch_export.source.hogql_query == hogql_batch_export_data["hogql_query"]
@@ -617,19 +630,48 @@ def test_create_batch_export_with_hogql_model(
"name": "hogql",
"schema": None,
"hogql_query": hogql_batch_export_data["hogql_query"],
+ "user_id": user.pk,
}
@pytest.mark.usefixtures("hogql_batch_exports_enabled")
[email protected]("access_level", ["viewer", "none"])
def test_create_batch_export_with_hogql_model_allows_query_without_placeholders(
- client: HttpClient, temporal, organization, team, user, hogql_batch_export_data
+ client: HttpClient, temporal, organization, team, user, hogql_batch_export_data, access_level: str
):
- """A query without interval placeholders is valid: every run exports all rows it returns."""
+ organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ organization.save()
+ credential = DataWarehouseCredential.objects.create(team=team, access_key="key", access_secret="secret")
+ table = DataWarehouseTable.objects.create(
+ team=team,
+ name="export_table",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ credential=credential,
+ url_pattern="s3://test-bucket/export/*",
+ columns={"id": "String"},
+ )
+ AccessControl.objects.create(
+ team=team,
+ resource="warehouse_table",
+ resource_id=str(table.pk),
+ access_level=access_level,
+ organization_member=OrganizationMembership.objects.get(organization=organization, user=user),
+ )
client.force_login(user)
- hogql_query = "SELECT event AS event FROM events"
+ hogql_query = "SELECT id FROM export_table"
response = create_batch_export(client, team.pk, {**hogql_batch_export_data, "hogql_query": hogql_query})
+ if access_level == "none":
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "hogql_query"
+ assert "You don't have access to table `export_table`" in response.json()["detail"]
+ assert not BatchExport.objects.filter(team=team).exists()
+ assert not BatchExportSource.objects.for_team(team.pk).exists()
+ return
+
assert response.status_code == status.HTTP_201_CREATED, response.json()
batch_export = BatchExport.objects.select_related("source").get(id=response.json()["id"])
assert batch_export.source is not None
diff --git a/products/batch_exports/backend/tests/api/test_update.py b/products/batch_exports/backend/tests/api/test_update.py
index 6d0fded8f4ab..5c788eebe40b 100644
--- a/products/batch_exports/backend/tests/api/test_update.py
+++ b/products/batch_exports/backend/tests/api/test_update.py
@@ -9,8 +9,11 @@ from django.test.client import Client as HttpClient
from asgiref.sync import async_to_sync
from rest_framework import status
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership
from posthog.models.integration import Integration
+from products.access_control.backend.models.access_control import AccessControl
from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination
from products.batch_exports.backend.service import sync_batch_export
from products.batch_exports.backend.tests.api.conftest import (
@@ -18,12 +21,14 @@ from products.batch_exports.backend.tests.api.conftest import (
assert_is_weekly_schedule,
describe_schedule,
)
+from products.batch_exports.backend.tests.api.fixtures import create_user
from products.batch_exports.backend.tests.api.operations import (
create_batch_export_ok,
get_batch_export_ok,
patch_batch_export,
put_batch_export,
)
+from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable
pytestmark = [
pytest.mark.django_db,
@@ -85,6 +90,8 @@ def test_can_put_config(client: HttpClient, temporal, encryption_codec, organiza
old_schedule = describe_schedule(temporal, batch_export["id"])
assert old_schedule.schedule.spec.intervals[0].every == dt.timedelta(hours=1)
+ editor = create_user("[email protected]", "Test User", organization)
+ client.force_login(editor)
# We should be able to update if we specify all fields
new_destination_data = {**destination_data}
@@ -94,10 +101,12 @@ def test_can_put_config(client: HttpClient, temporal, encryption_codec, organiza
"destination": new_destination_data,
"interval": "day",
"start_at": "2022-07-19 00:00:00",
+ "last_modified_by": user.pk,
}
response = put_batch_export(client, team.pk, batch_export["id"], new_batch_export_data_2)
assert response.status_code == status.HTTP_200_OK
+ assert BatchExport.objects.get(id=batch_export["id"]).last_modified_by_id == editor.pk
# get the batch export and validate e.g. that interval has been updated to day
batch_export = get_batch_export_ok(client, team.pk, batch_export["id"])
@@ -116,6 +125,7 @@ def test_can_put_config(client: HttpClient, temporal, encryption_codec, organiza
decoded_payload = async_to_sync(encryption_codec.decode)(new_schedule.schedule.action.args)
args = json.loads(decoded_payload[0].data)
assert args["bucket_name"] == "my-new-production-s3-bucket"
+ assert args["batch_export_model"]["user_id"] is None
# Credentials are resolved from the integration at run time, never carried in the schedule.
assert args["integration_id"] == aws_s3_integration.id
assert args.get("aws_secret_access_key") is None
@@ -160,6 +170,9 @@ def test_can_patch_config(
)
old_schedule = describe_schedule(temporal, batch_export["id"])
+ editor = create_user("[email protected]", "Test User", organization)
+ client.force_login(editor)
+
# We should be able to update the destination config, excluding the aws
# credentials. The existing values should be preserved.
new_destination_data = {
@@ -175,10 +188,12 @@ def test_can_patch_config(
new_batch_export_data = {
"name": "my-production-s3-bucket-destination",
"destination": new_destination_data,
+ "last_modified_by": user.pk,
}
response = patch_batch_export(client, team.pk, batch_export["id"], new_batch_export_data)
assert response.status_code == status.HTTP_200_OK, response.json()
+ assert BatchExport.objects.get(id=batch_export["id"]).last_modified_by_id == editor.pk
# get the batch export and validate e.g. that bucket_name and interval
# has been preserved.
@@ -206,6 +221,7 @@ def test_can_patch_config(
args = json.loads(decoded_payload[0].data)
assert args["bucket_name"] == "my-new-production-s3-bucket"
assert new_schedule.schedule.spec.time_zone_name == timezone
+ assert args["batch_export_model"]["user_id"] is None
@pytest.mark.parametrize(
@@ -707,6 +723,7 @@ def test_can_patch_hogql_query(
"hogql_query": "SELECT toString(uuid) AS uuid, 'test' AS test, toInt(plus(1, 1)) AS n FROM events",
},
"hogql_query": None,
+ "user_id": None,
}
for patch_data, expected_schema in [
@@ -775,21 +792,32 @@ def test_patch_hogql_model_batch_export(
client.force_login(user)
batch_export = create_batch_export_ok(client, team.pk, hogql_batch_export_data)
source_id = BatchExport.objects.get(id=batch_export["id"]).source_id
+ editor = create_user("[email protected]", "Test User", organization)
+ client.force_login(editor)
hogql_batch_exports_enabled.return_value = hogql_enabled
# A change that does not touch the source keeps it as it is.
- response = patch_batch_export(client, team.pk, batch_export["id"], {"name": "renamed"})
+ response = patch_batch_export(
+ client, team.pk, batch_export["id"], {"name": "renamed", "last_modified_by": user.pk, "user_id": user.pk}
+ )
if not hogql_enabled:
assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
unchanged = get_batch_export_ok(client, team.pk, batch_export["id"])
assert unchanged["name"] == batch_export["name"]
assert unchanged["hogql_query"] == hogql_batch_export_data["hogql_query"]
+ assert BatchExport.objects.get(id=batch_export["id"]).last_modified_by_id == user.pk
return
assert response.status_code == status.HTTP_200_OK, response.json()
renamed = get_batch_export_ok(client, team.pk, batch_export["id"])
assert renamed["name"] == "renamed"
assert renamed["hogql_query"] == hogql_batch_export_data["hogql_query"]
+ assert BatchExport.objects.get(id=batch_export["id"]).last_modified_by_id == editor.pk
+ schedule = describe_schedule(temporal, batch_export["id"])
+ decoded_payload = async_to_sync(encryption_codec.decode)(schedule.schedule.action.args)
+ args = json.loads(decoded_payload[0].data)
+ assert args["batch_export_model"]["user_id"] == editor.pk
+ assert args["batch_export_model"]["hogql_query"] == hogql_batch_export_data["hogql_query"]
# A query without interval placeholders is as valid as a bounded one.
new_hogql_query = "SELECT uuid AS uuid, created_at AS created_at FROM events"
@@ -813,9 +841,77 @@ def test_patch_hogql_model_batch_export(
"name": "hogql",
"schema": None,
"hogql_query": new_hogql_query,
+ "user_id": editor.pk,
}
[email protected]("hogql_batch_exports_enabled")
[email protected]("access_level,include_query", [("viewer", False), ("none", False), ("none", True)])
+def test_patch_hogql_model_batch_export_checks_editor_table_access(
+ client: HttpClient,
+ temporal,
+ encryption_codec,
+ organization,
+ team,
+ user,
+ hogql_batch_export_data,
+ access_level: str,
+ include_query: bool,
+) -> None:
+ organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ organization.save()
+ credential = DataWarehouseCredential.objects.create(team=team, access_key="key", access_secret="secret")
+ table = DataWarehouseTable.objects.create(
+ team=team,
+ name="export_table",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ credential=credential,
+ url_pattern="s3://test-bucket/export/*",
+ columns={"id": "String"},
+ )
+ hogql_query = "SELECT id FROM export_table"
+ client.force_login(user)
+ batch_export = create_batch_export_ok(client, team.pk, {**hogql_batch_export_data, "hogql_query": hogql_query})
+ old_schedule = describe_schedule(temporal, batch_export["id"])
+ editor = create_user("[email protected]", "Test User", organization)
+ AccessControl.objects.create(
+ team=team,
+ resource="warehouse_table",
+ resource_id=str(table.pk),
+ access_level=access_level,
+ organization_member=OrganizationMembership.objects.get(organization=organization, user=editor),
+ )
+ client.force_login(editor)
+ patch_data: dict[str, str | int] = {"name": "renamed", "last_modified_by": user.pk}
+ if include_query:
+ patch_data["hogql_query"] = "SELECT id AS exported_id FROM export_table"
+
+ response = patch_batch_export(client, team.pk, batch_export["id"], patch_data)
+
+ saved = BatchExport.objects.select_related("source").get(id=batch_export["id"])
+ assert saved.source is not None
+ assert saved.source.hogql_query == hogql_query
+ schedule = describe_schedule(temporal, batch_export["id"])
+ if access_level == "none":
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "hogql_query"
+ assert "You don't have access to table `export_table`" in response.json()["detail"]
+ assert saved.last_modified_by_id == user.pk
+ assert saved.name == batch_export["name"]
+ assert schedule.schedule == old_schedule.schedule
+ return
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert saved.last_modified_by_id == editor.pk
+ assert saved.name == "renamed"
+ decoded_payload = async_to_sync(encryption_codec.decode)(schedule.schedule.action.args)
+ args = json.loads(decoded_payload[0].data)
+ assert args["batch_export_model"]["user_id"] == editor.pk
+ assert args["batch_export_model"]["hogql_query"] == hogql_query
+
+
@pytest.mark.usefixtures("hogql_batch_exports_enabled")
@pytest.mark.parametrize("hogql_query", ["SELECT does_not_exist AS does_not_exist FROM events", None])
def test_patch_hogql_model_batch_export_validates_new_query(
diff --git a/products/batch_exports/backend/tests/conftest.py b/products/batch_exports/backend/tests/conftest.py
index c3a6366460c0..2d001ea3a4c0 100644
--- a/products/batch_exports/backend/tests/conftest.py
+++ b/products/batch_exports/backend/tests/conftest.py
@@ -1,9 +1,10 @@
import random
+from collections.abc import AsyncIterator
import pytest_asyncio
from asgiref.sync import sync_to_async
-from posthog.models import Organization, Team
+from posthog.models import Organization, Team, User
@pytest_asyncio.fixture
@@ -28,3 +29,14 @@ async def ateam(aorganization):
# Calling delete_batch_exports() here can hang indefinitely because
# sync_to_async threads blocked on gRPC cannot be cancelled by asyncio.
await sync_to_async(team.delete)()
+
+
+@pytest_asyncio.fixture
+async def auser(aorganization: Organization, ateam: Team) -> AsyncIterator[User]:
+ user = await sync_to_async(User.objects.create_and_join)(
+ organization=aorganization, email="[email protected]", password=None
+ )
+
+ yield user
+
+ await sync_to_async(user.delete)()
diff --git a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py
index 8580dba3dfd7..ac04b0d7cb51 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py
@@ -19,11 +19,14 @@ from asgiref.sync import sync_to_async
from rest_framework import status
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+from posthog.constants import AvailableFeature
from posthog.exceptions import ClickHouseQueryTimeOut
+from posthog.models import Organization, OrganizationMembership, PropertyDefinition
from posthog.models.event.util import bulk_create_events
from posthog.models.scoping import team_scope
from posthog.temporal.tests.utils.events import generate_test_events
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
from products.batch_exports.backend.api.file_download import (
COUNT_ROWS_TIMEOUT_MESSAGE,
DEFAULT_MAX_SIZE_MB,
@@ -814,12 +817,16 @@ class TestFileDownloadHogQL:
"file": {"format": "Parquet"},
"model": "hogql",
"hogql_query": hogql_query,
+ "last_modified_by": user.pk + 1,
+ "last_modified_by_id": user.pk + 1,
+ "user_id": user.pk + 1,
**bounds,
},
content_type="application/json",
)
assert response.status_code == status.HTTP_202_ACCEPTED, response.json()
+ assert set(response.json()) == {"id"}
with team_scope(team_id=team.pk, canonical=True):
run = await BatchExportRun.objects.select_related(
@@ -832,6 +839,7 @@ class TestFileDownloadHogQL:
on_demand = run.batch_export_on_demand
assert on_demand is not None
assert on_demand.model == "hogql"
+ assert on_demand.last_modified_by_id == user.pk
assert on_demand.source is not None
assert on_demand.source.hogql_query == hogql_query
assert on_demand.source.team_id == team.pk
@@ -841,6 +849,7 @@ class TestFileDownloadHogQL:
batch_export_model = mock_start_file_download_export.call_args.kwargs["batch_export_model"]
assert batch_export_model.name == "hogql"
assert batch_export_model.hogql_query == hogql_query
+ assert batch_export_model.user_id == user.pk
assert mock_start_file_download_export.call_args.kwargs["max_size_mb"] == DEFAULT_MAX_SIZE_MB
assert mock_start_file_download_export.call_args.kwargs["data_interval_start"] == run.data_interval_start
assert mock_start_file_download_export.call_args.kwargs["data_interval_end"] == run.data_interval_end
@@ -1026,6 +1035,45 @@ class TestFileDownloadHogQL:
assert response.status_code == status.HTTP_200_OK, response.json()
assert response.json() == {"count": expected_count}
+ @pytest.mark.usefixtures("enable_hogql_flag")
+ @pytest.mark.django_db(transaction=True)
+ async def test_count_rows_masks_properties_in_where(
+ self, async_client: AsyncClient, team, user, hogql_export_test_events
+ ) -> None:
+ await Organization.objects.filter(pk=team.organization_id).aupdate(
+ available_product_features=[
+ {"key": AvailableFeature.PROPERTY_ACCESS_CONTROL, "name": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ )
+ membership = await OrganizationMembership.objects.aget(user=user, organization_id=team.organization_id)
+ membership.level = OrganizationMembership.Level.MEMBER
+ await membership.asave(update_fields=["level"])
+ property_definition = await PropertyDefinition.objects.acreate(
+ team=team, name="$browser", property_type="String", type=PropertyDefinition.Type.EVENT
+ )
+ rule = await PropertyAccessControl.objects.acreate(
+ team=team,
+ property_definition=property_definition,
+ organization_member=membership,
+ access_level="read",
+ )
+ await async_client.aforce_login(user)
+
+ for access_level, expected_count in [("read", len(hogql_export_test_events)), ("none", 0)]:
+ rule.access_level = access_level
+ await rule.asave(update_fields=["access_level"])
+ response = await async_client.post(
+ f"/api/projects/{team.pk}/file_download_batch_exports/count_rows",
+ {
+ "model": "hogql",
+ "hogql_query": "SELECT event FROM events WHERE properties.$browser = 'Chrome'",
+ },
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {"count": expected_count}
+
@pytest.mark.parametrize(
"body,expected_error_fragment",
[
diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_with_local_object_storage.py b/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_with_local_object_storage.py
index b2af89513466..4929cfa7dccd 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_with_local_object_storage.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_with_local_object_storage.py
@@ -381,6 +381,7 @@ async def test_s3_export_workflow_with_local_object_storage_with_hogql_model(
clickhouse_client,
object_storage_client,
ateam,
+ auser,
s3_compatible_batch_export,
bucket_name,
interval,
@@ -400,7 +401,7 @@ async def test_s3_export_workflow_with_local_object_storage_with_hogql_model(
`events_table` is pinned to `sharded_events` because the HogQL `events` table reads it,
while the fixture would otherwise default to `events_recent` for a recent interval.
"""
- model = BatchExportModel(name="hogql", schema=None, hogql_query=hogql_query)
+ model = BatchExportModel(name="hogql", schema=None, hogql_query=hogql_query, user_id=auser.pk)
await run_s3_batch_export_workflow(
model=model,
diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py b/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py
index c21657fda45c..92669b7aaafd 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py
@@ -333,7 +333,9 @@ async def assert_clickhouse_records_in_s3(
# Re-running the query itself yields the expected rows, with the same interval bounds
# substituted as the run exported with.
producer = ClickHouseTestProducer(
- model=HogQLQueryRecordBatchModel(team_id=team_id, hogql_query=batch_export_model.hogql_query)
+ model=HogQLQueryRecordBatchModel(
+ team_id=team_id, hogql_query=batch_export_model.hogql_query, user_id=batch_export_model.user_id
+ )
)
else:
producer = ClickHouseTestProducer()
diff --git a/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py b/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py
index 87b5a60d96ac..bfd9f84c0ba4 100644
--- a/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py
+++ b/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py
@@ -18,6 +18,7 @@ import pytest_asyncio
from structlog.testing import capture_logs
from temporalio.testing import ActivityEnvironment
+from posthog.models import Team
from posthog.models.utils import uuid7
from posthog.sync import database_sync_to_async
from posthog.temporal.common.clickhouse import (
@@ -1302,6 +1303,29 @@ async def test_insert_into_stage_activity_applies_settings_and_log_comment(
class TestHogQLModel:
"""Tests for the 'hogql' model, which exports the results of a user-defined HogQL query."""
+ async def test_missing_actor_fails_without_executing_query(
+ self,
+ ateam: Team,
+ activity_environment: ActivityEnvironment,
+ mock_clickhouse_client: MockClickHouseClient,
+ ) -> None:
+ inputs = BatchExportInsertIntoInternalStageInputs(
+ team_id=ateam.pk,
+ batch_export_id=str(uuid.uuid4()),
+ data_interval_start=(TEST_DATA_INTERVAL_END - dt.timedelta(hours=1)).isoformat(),
+ data_interval_end=TEST_DATA_INTERVAL_END.isoformat(),
+ batch_export_model=BatchExportModel(name="hogql", schema=None, hogql_query="SELECT 1", user_id=None),
+ )
+
+ with patch("products.batch_exports.backend.temporal.pipeline.internal_stage._execute_query") as execute_query:
+ result = await activity_environment.run(insert_into_internal_stage_activity, inputs)
+
+ assert result.error is not None
+ assert result.error.type == "UnsupportedHogQLQueryError"
+ assert "needs an active user" in result.error.message
+ execute_query.assert_not_called()
+ mock_clickhouse_client.expect_query_count(0)
+
@pytest_asyncio.fixture
async def hogql_model_test_data(
self, clickhouse_client, ateam, data_interval_start, data_interval_end, truncate_clickhouse_tables
@@ -1439,6 +1463,7 @@ class TestHogQLModel:
activity_environment,
object_storage_client,
ateam,
+ auser,
data_interval_start,
data_interval_end,
hogql_query,
@@ -1462,7 +1487,7 @@ class TestHogQLModel:
team_id=ateam.pk,
data_interval_start=data_interval_start,
data_interval_end=data_interval_end,
- model=BatchExportModel(name="hogql", schema=None, hogql_query=hogql_query),
+ model=BatchExportModel(name="hogql", schema=None, hogql_query=hogql_query, user_id=auser.pk),
)
assert all(list(row.keys()) == expected_columns for row in exported_rows)
@@ -1477,6 +1502,7 @@ class TestHogQLModel:
activity_environment,
object_storage_client,
ateam,
+ auser,
data_interval_start,
data_interval_end,
):
@@ -1509,6 +1535,7 @@ class TestHogQLModel:
"SELECT uuid AS uuid, timestamp AS timestamp FROM events "
"WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}"
),
+ user_id=auser.pk,
),
)
@@ -1526,6 +1553,7 @@ class TestHogQLModel:
activity_environment,
object_storage_client,
ateam,
+ auser,
data_interval_start,
data_interval_end,
):
@@ -1552,7 +1580,10 @@ class TestHogQLModel:
data_interval_start=data_interval_start,
data_interval_end=data_interval_end,
model=BatchExportModel(
- name="hogql", schema=None, hogql_query="SELECT event_id, event, distinct_id FROM events_view"
+ name="hogql",
+ schema=None,
+ hogql_query="SELECT event_id, event, distinct_id FROM events_view",
+ user_id=auser.pk,
),
)
@@ -1568,7 +1599,9 @@ class TestHogQLModel:
team_id=ateam.pk,
data_interval_start=data_interval_start,
data_interval_end=data_interval_end,
- model=BatchExportModel(name="hogql", schema=None, hogql_query="SELECT * FROM events_view"),
+ model=BatchExportModel(
+ name="hogql", schema=None, hogql_query="SELECT * FROM events_view", user_id=auser.pk
+ ),
)
assert sorted((row["event_id"], row["event"], row["distinct_id"]) for row in exported_rows_2) == sorted(
(e["uuid"], e["event"], e["distinct_id"]) for e in events
@@ -1585,6 +1618,7 @@ class TestHogQLModel:
activity_environment,
object_storage_client,
ateam,
+ auser,
clickhouse_client,
data_interval_start,
data_interval_end,
@@ -1604,7 +1638,9 @@ class TestHogQLModel:
team_id=ateam.pk,
data_interval_start=data_interval_start,
data_interval_end=data_interval_end,
- model=BatchExportModel(name="hogql", schema=None, hogql_query="SELECT event AS event FROM events"),
+ model=BatchExportModel(
+ name="hogql", schema=None, hogql_query="SELECT event AS event FROM events", user_id=auser.pk
+ ),
batch_export_id=batch_export_id,
)
diff --git a/products/batch_exports/backend/tests/temporal/test_record_batch_model.py b/products/batch_exports/backend/tests/temporal/test_record_batch_model.py
index f060c4405a2b..a0277d137e80 100644
--- a/products/batch_exports/backend/tests/temporal/test_record_batch_model.py
+++ b/products/batch_exports/backend/tests/temporal/test_record_batch_model.py
@@ -1,7 +1,9 @@
import json
import datetime as dt
+from typing import TYPE_CHECKING
import pytest
+from unittest.mock import patch
from django.conf import settings
from django.test import override_settings
@@ -11,14 +13,21 @@ import pyarrow as pa
from posthog.hogql.hogql import ast
from posthog.hogql.printer import prepare_ast_for_printing, print_prepared_ast
+from posthog.constants import AvailableFeature
from posthog.credentials import AWSKeyPair
+from posthog.models import OrganizationMembership, PropertyDefinition, User
from posthog.models.event.sql import EVENTS_PROPERTIES_JSON_TYPE, PERSON_PROPERTIES_JSON_TYPE
from posthog.models.utils import uuid7
from posthog.sync import database_sync_to_async
from posthog.temporal.common.clickhouse import ClickHouseClient
from posthog.temporal.tests.utils.events import generate_test_events_in_clickhouse
-from products.batch_exports.backend.hogql_source import UnsupportedHogQLQueryError
+from products.access_control.backend.models import AccessControl
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
+from products.batch_exports.backend.hogql_source import (
+ UnsupportedHogQLQueryError,
+ validate_hogql_query_for_batch_export,
+)
from products.batch_exports.backend.service import BatchExportModel, BatchExportSchema
from products.batch_exports.backend.temporal.batch_exports import iter_records
from products.batch_exports.backend.temporal.filters import compose_filters_clause
@@ -29,6 +38,10 @@ from products.batch_exports.backend.temporal.record_batch_model import (
)
from products.batch_exports.backend.temporal.sql.sessions import SESSIONS_LOOKBACK_DAYS
from products.batch_exports.backend.tests.temporal.utils.clickhouse import truncate_events, truncate_sessions
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+
+if TYPE_CHECKING:
+ from posthog.models import Organization, Team
pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]
@@ -337,9 +350,11 @@ class TestSessionsRecordBatchModelSelection:
class TestHogQLQueryRecordBatchModel:
- async def test_as_query_with_parameters(self, ateam, data_interval_start, data_interval_end):
+ async def test_as_query_with_parameters(self, ateam, auser, data_interval_start, data_interval_end):
model = HogQLQueryRecordBatchModel(
- team_id=ateam.id, hogql_query="SELECT event AS event, distinct_id AS distinct_id FROM events"
+ team_id=ateam.id,
+ hogql_query="SELECT event AS event, distinct_id AS distinct_id FROM events",
+ user_id=auser.pk,
)
printed_query, query_parameters = await model.as_query_with_parameters(data_interval_start, data_interval_end)
@@ -351,9 +366,12 @@ class TestHogQLQueryRecordBatchModel:
assert f"toDateTime64('{data_interval_end:%Y-%m-%d %H:%M:%S.%f}', 6, 'UTC')" not in printed_query
assert model.wait_for_data_interval_end is False
- async def test_as_query_with_parameters_applies_data_interval(self, ateam, data_interval_start, data_interval_end):
+ async def test_as_query_with_parameters_applies_data_interval(
+ self, ateam, auser, data_interval_start, data_interval_end
+ ):
model = HogQLQueryRecordBatchModel(
team_id=ateam.id,
+ user_id=auser.pk,
hogql_query=(
"SELECT event AS event, timestamp AS timestamp FROM events "
"WHERE event = 'test' AND timestamp >= {data_interval_start} "
@@ -370,7 +388,7 @@ class TestHogQLQueryRecordBatchModel:
assert "equals(event, %(hogql_val_" in printed_query
assert model.wait_for_data_interval_end is True
- async def test_as_query_with_parameters_selects_only_rows_in_data_interval(self, clickhouse_client, ateam):
+ async def test_as_query_with_parameters_selects_only_rows_in_data_interval(self, clickhouse_client, ateam, auser):
await truncate_events(clickhouse_client)
data_interval_start = dt.datetime(2021, 1, 15, 10, 0, 0, tzinfo=dt.UTC)
data_interval_end = dt.datetime(2021, 1, 15, 11, 0, 0, tzinfo=dt.UTC)
@@ -386,6 +404,7 @@ class TestHogQLQueryRecordBatchModel:
)
model = HogQLQueryRecordBatchModel(
team_id=ateam.pk,
+ user_id=auser.pk,
hogql_query=(
"SELECT uuid AS uuid, timestamp AS timestamp FROM events "
"WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}"
@@ -399,9 +418,11 @@ class TestHogQLQueryRecordBatchModel:
assert {row["uuid"] for row in rows} == {event["uuid"] for event in events_in_range}
- async def test_as_insert_into_s3_query_with_parameters(self, ateam, data_interval_start, data_interval_end):
+ async def test_as_insert_into_s3_query_with_parameters(self, ateam, auser, data_interval_start, data_interval_end):
model = HogQLQueryRecordBatchModel(
- team_id=ateam.id, hogql_query="SELECT event AS event, distinct_id AS distinct_id FROM events"
+ team_id=ateam.id,
+ hogql_query="SELECT event AS event, distinct_id AS distinct_id FROM events",
+ user_id=auser.pk,
)
printed_query, query_parameters = await model.as_insert_into_s3_query_with_parameters(
data_interval_start=data_interval_start,
@@ -521,6 +542,112 @@ class TestHogQLQueryRecordBatchModel:
with pytest.raises(UnsupportedHogQLQueryError):
resolve_batch_exports_model(team_id=1, batch_export_model=BatchExportModel(name="hogql", schema=None))
+ @pytest.mark.parametrize("actor_state", ["missing", "deleted", "inactive", "nonmember", "project-denied"])
+ async def test_rechecks_actor_access_at_runtime(
+ self, ateam: "Team", aorganization: "Organization", auser: User, actor_state: str
+ ) -> None:
+ query = "SELECT event AS event FROM events"
+ await database_sync_to_async(validate_hogql_query_for_batch_export)(query, ateam, user=auser)
+ payload = BatchExportModel(name="hogql", schema=None, hogql_query=query, user_id=auser.pk)
+ _, model, _, _, _, _ = resolve_batch_exports_model(ateam.pk, payload)
+ await model.as_query_with_parameters(None, None)
+
+ if actor_state == "missing":
+ _, model, _, _, _, _ = resolve_batch_exports_model(
+ ateam.pk, BatchExportModel(name="hogql", schema=None, hogql_query=query)
+ )
+ elif actor_state == "deleted":
+ await User.objects.filter(pk=auser.pk).adelete()
+ elif actor_state == "inactive":
+ await User.objects.filter(pk=auser.pk).aupdate(is_active=False)
+ elif actor_state == "nonmember":
+ await OrganizationMembership.objects.filter(user=auser, organization=aorganization).adelete()
+ else:
+ aorganization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ await aorganization.asave()
+ membership = await OrganizationMembership.objects.aget(user=auser, organization=aorganization)
+ await AccessControl.objects.acreate(
+ team=ateam,
+ resource="project",
+ resource_id=str(ateam.pk),
+ organization_member=membership,
+ access_level="none",
+ )
+
+ with pytest.raises(UnsupportedHogQLQueryError, match="Save the export again"):
+ await model.as_query_with_parameters(None, None)
+
+ @pytest.mark.parametrize("use_new_events_schema", [False, True])
+ async def test_rechecks_user_property_restrictions_at_runtime(
+ self, ateam: "Team", aorganization: "Organization", auser: User, use_new_events_schema: bool
+ ) -> None:
+ aorganization.available_product_features = [
+ {"key": AvailableFeature.PROPERTY_ACCESS_CONTROL, "name": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ await aorganization.asave()
+ membership = await OrganizationMembership.objects.aget(user=auser, organization=aorganization)
+ prop = await PropertyDefinition.objects.acreate(
+ team=ateam, name="secret_field", type=PropertyDefinition.Type.EVENT, property_type="String"
+ )
+ query = (
+ "WITH source AS (SELECT properties.secret_field AS secret, properties AS all_properties FROM events) "
+ "SELECT secret, all_properties FROM source"
+ )
+ with override_settings(CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA=use_new_events_schema):
+ await database_sync_to_async(validate_hogql_query_for_batch_export)(query, ateam, user=auser)
+ _, model, _, _, _, _ = resolve_batch_exports_model(
+ ateam.pk, BatchExportModel(name="hogql", schema=None, hogql_query=query, user_id=auser.pk)
+ )
+ before, _ = await model.as_query_with_parameters(None, None)
+ assert "NULL AS secret" not in before
+ assert "JSONDropKeys" not in before
+
+ await PropertyAccessControl.objects.acreate(
+ team=ateam, property_definition=prop, organization_member=membership, access_level="none"
+ )
+ await database_sync_to_async(validate_hogql_query_for_batch_export)(query, ateam, user=auser)
+ after, parameters = await model.as_insert_into_s3_query_with_parameters(
+ None, None, "https://example.com/staging", None, 1
+ )
+
+ assert "NULL AS secret" in after
+ assert "JSONDropKeys" in after
+ assert any(isinstance(value, list) and "secret_field" in value for value in parameters.values())
+
+ async def test_rechecks_table_access_at_runtime(
+ self, ateam: "Team", aorganization: "Organization", auser: User
+ ) -> None:
+ aorganization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ await aorganization.asave()
+ view = await DataWarehouseSavedQuery.objects.acreate(
+ team=ateam,
+ name="export_view",
+ query={"kind": "HogQLQuery", "query": "SELECT event FROM events"},
+ columns={"event": "String"},
+ )
+ query = "SELECT event FROM export_view"
+ with patch("posthog.hogql.database.database.feature_enabled_or_false", return_value=True):
+ await database_sync_to_async(validate_hogql_query_for_batch_export)(query, ateam, user=auser)
+ _, model, _, _, _, _ = resolve_batch_exports_model(
+ ateam.pk, BatchExportModel(name="hogql", schema=None, hogql_query=query, user_id=auser.pk)
+ )
+ await model.as_query_with_parameters(None, None)
+ membership = await OrganizationMembership.objects.aget(user=auser, organization=aorganization)
+ await AccessControl.objects.acreate(
+ team=ateam,
+ resource="warehouse_view",
+ resource_id=str(view.pk),
+ organization_member=membership,
+ access_level="none",
+ )
+
+ with pytest.raises(UnsupportedHogQLQueryError, match="You don't have access to table `export_view`"):
+ await model.as_query_with_parameters(None, None)
+
@pytest.mark.parametrize("use_new_events_schema", [False, True])
async def test_custom_export_recompilation_preserves_column_names(ateam, use_new_events_schema):
diff --git a/products/batch_exports/backend/tests/test_hogql_source.py b/products/batch_exports/backend/tests/test_hogql_source.py
index c7bac72c62b4..89eb04eed793 100644
--- a/products/batch_exports/backend/tests/test_hogql_source.py
+++ b/products/batch_exports/backend/tests/test_hogql_source.py
@@ -10,12 +10,15 @@ from products.batch_exports.backend.hogql_source import (
validate_hogql_query_for_batch_export,
)
+if typing.TYPE_CHECKING:
+ from posthog.models import Team, User
+
pytestmark = pytest.mark.django_db
-async def _validate(hogql_query: str, team) -> None:
+async def _validate(hogql_query: str, team: "Team", user: "User") -> None:
# Resolving the query reads from Postgres to build the team database, so run it off the event loop.
- await database_sync_to_async(validate_hogql_query_for_batch_export)(hogql_query, team)
+ await database_sync_to_async(validate_hogql_query_for_batch_export)(hogql_query, team, user=user)
@pytest.mark.parametrize(
@@ -84,8 +87,8 @@ async def _validate(hogql_query: str, team) -> None:
"cte-with-placeholders",
],
)
-async def test_accepts_valid_queries(ateam, hogql_query):
- await _validate(hogql_query, ateam)
+async def test_accepts_valid_queries(ateam, auser, hogql_query):
+ await _validate(hogql_query, ateam, auser)
@pytest.mark.parametrize(
@@ -111,9 +114,9 @@ async def test_accepts_valid_queries(ateam, hogql_query):
"unknown-field-in-placeholder-comparison",
],
)
-async def test_rejects_unsupported_queries(ateam, hogql_query, expected_message):
+async def test_rejects_unsupported_queries(ateam, auser, hogql_query, expected_message):
with pytest.raises(UnsupportedHogQLQueryError, match=expected_message):
- await _validate(hogql_query, ateam)
+ await _validate(hogql_query, ateam, auser)
@pytest.mark.parametrize("team_modifiers", [None, {"convertToProjectTimezone": False}])