: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
feat(s3): Role based authentication for s3 batch export (#69690)
Tomás Farías Santanadea402e48098
diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex 3dfa5c065d38..ad46cb7c5bd8 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -51,6 +51,7 @@ from posthog.models.integration import (SLACK_INTEGRATION_KINDS,AnthropicIntegration,AwsS3Integration,+ AwsS3RoleBasedIntegration,AzureBlobIntegration,AzureBlobIntegrationError,ClickUpIntegration,@@ -633,22 +634,20 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerialelif validated_data["kind"] == "aws-s3":config = validated_data.get("config", {})- name = config.get("name")- aws_access_key_id = config.get("aws_access_key_id")- aws_secret_access_key = config.get("aws_secret_access_key")- if not (name and aws_access_key_id and aws_secret_access_key):- raise ValidationError("Name, access key ID, and secret access key must be provided")- if not all(isinstance(value, str) for value in (name, aws_access_key_id, aws_secret_access_key)):- raise ValidationError("Name, access key ID, and secret access key must be strings")+ get_organization = self.context.get("get_organization")+ if get_organization is None:+ raise ValidationError("Organization context is missing")+ organization_id = str(get_organization().id)++ integration = AwsS3RoleBasedIntegration if "aws_role_arn" in config else AwsS3Integrationtry:- instance = AwsS3Integration.integration_from_config(+ instance = integration.integration_from_config(team_id=team_id,- name=name,- aws_access_key_id=aws_access_key_id,- aws_secret_access_key=aws_secret_access_key,created_by=request.user,+ organization_id=organization_id,+ **config,)except S3CredentialIntegrationError as e:raise ValidationError(str(e))diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex de13ac0c42bd..e298cdcba082 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -684,17 +684,20 @@ class TestAwsS3Integration:[({"aws_access_key_id": "k", "aws_secret_access_key": "s"},- "Name, access key ID, and secret access key must be provided",+ "A name is required for an AWS S3 integration",),({"name": "n", "aws_secret_access_key": "s"},- "Name, access key ID, and secret access key must be provided",+ "Access key ID is required for an AWS S3 integration",),- ({"name": "n", "aws_access_key_id": "k"}, "Name, access key ID, and secret access key must be provided"),- ({}, "Name, access key ID, and secret access key must be provided"),+ (+ {"name": "n", "aws_access_key_id": "k"},+ "Secret access key is required for an AWS S3 integration",+ ),+ ({}, "A name is required for an AWS S3 integration"),({"name": "n", "aws_access_key_id": "k", "aws_secret_access_key": 1},- "Name, access key ID, and secret access key must be strings",+ "Secret access key is required for an AWS S3 integration",),],)@@ -711,6 +714,79 @@ class TestAwsS3Integration:assert response.json()["detail"] == expected_error_message+class TestAwsS3RoleBasedIntegration:+ @pytest.fixture(autouse=True)+ def setup_integration(self, db):+ self.organization = Organization.objects.create(name="Test Org")+ self.team = Team.objects.create(organization=self.organization, name="Test Team")+ self.user = User.objects.create_and_join(+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN+ )++ def test_create_with_valid_config(self, client: HttpClient):+ client.force_login(self.user)++ role = "arn:aws:iam::123456789012:role/my-role"+ response = client.post(+ f"/api/environments/{self.team.pk}/integrations",+ {+ "kind": "aws-s3",+ "config": {+ "name": "prod-aws",+ "aws_role_arn": role,+ },+ },+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert response.json()["kind"] == "aws-s3"++ integration = Integration.objects.get(id=response.json()["id"])+ assert integration.kind == "aws-s3"+ assert integration.team == self.team+ assert integration.integration_id == "prod-aws"+ assert integration.config == {"name": "prod-aws", "aws_role_arn": role}+ assert integration.sensitive_config == {}++ def test_create_rejects_duplicate_role_in_different_org(self, client: HttpClient):+ another_org = Organization.objects.create(name="Test Org 2")+ another_team = Team.objects.create(organization=another_org, name="Test Team")+ another_user = User.objects.create_and_join(+ another_org, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN+ )+ client.force_login(another_user)+ payload = {+ "kind": "aws-s3",+ "config": {"name": "prod-aws", "aws_role_arn": "something"},+ }++ first = client.post(+ f"/api/environments/{another_team.pk}/integrations", payload, content_type="application/json"+ )+ assert first.status_code == status.HTTP_201_CREATED, first.json()++ client.force_login(self.user)+ second = client.post(f"/api/environments/{self.team.pk}/integrations", payload, content_type="application/json")+ assert second.status_code == status.HTTP_400_BAD_REQUEST+ assert "Cannot create AWS S3 integration: Invalid role" in second.json()["detail"]++ def test_create_rejects_duplicate_name(self, client: HttpClient):+ client.force_login(self.user)+ payload = {+ "kind": "aws-s3",+ "config": {"name": "prod-aws", "aws_role_arn": "something"},+ }++ first = client.post(f"/api/environments/{self.team.pk}/integrations", payload, content_type="application/json")+ assert first.status_code == status.HTTP_201_CREATED, first.json()++ second = client.post(f"/api/environments/{self.team.pk}/integrations", payload, content_type="application/json")+ assert second.status_code == status.HTTP_400_BAD_REQUEST+ assert "An integration named 'prod-aws' already exists" in second.json()["detail"]+ assert Integration.objects.filter(team=self.team, integration_id="prod-aws").count() == 1++class TestS3CompatibleIntegration:@pytest.fixture(autouse=True)def setup_integration(self, db):diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 43ff5d2de813..fd5a62807632 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -4,7 +4,7 @@ import jsonimport timeimport base64import hashlib-from collections.abc import Iterable+from collections.abc import Iterable, Mappingfrom dataclasses import dataclassfrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Any, Literal, NamedTuple, NoReturn, Optional, Self@@ -303,16 +303,22 @@ class Integration(models.Model):return self.integration_id or "unknown ID"if self.kind == Integration.IntegrationKind.AWS_S3:name = self.integration_id or "unknown ID"- # config["auth_type"] leaves room for a future OIDC / IAM-role mode; only keys exist today.- auth_label = self.config.get("auth_type", "access key")+account_id = self.config.get("aws_account_id")- detail = f"{auth_label}, AWS account {account_id}" if account_id else auth_label+ role = self.config.get("aws_role_arn")++ if role:+ detail = f"AWS role '{role}'"+ elif account_id:+ detail = f"AWS account {account_id}"+ else:+ detail = "access key"+return f"{name} ({detail})"if self.kind == Integration.IntegrationKind.S3_COMPATIBLE:name = self.integration_id or "unknown ID"- auth_label = self.config.get("auth_type", "access key")endpoint_url = self.config.get("endpoint_url")- detail = f"{auth_label}, {endpoint_url}" if endpoint_url else auth_label+ detail = f"access key, {endpoint_url}" if endpoint_url else "access key"return f"{name} ({detail})"if self.kind == Integration.IntegrationKind.SNOWFLAKE:name = self.integration_id or "unknown ID"@@ -3545,6 +3551,84 @@ def _create_unique_s3_integration(raise S3CredentialIntegrationError(f"An integration named '{name}' already exists")+def is_unique_aws_role_by_organization_id(aws_role_arn: str, organization_id: str) -> bool:+ """Check if the AWS role is only in one organization.++ This is used as a security measure to block multiple organizations from+ assuming the same role.++ In the future we may lift this restriction, but initially we want to make sure about+ AWS role ownership with this check. This complements other runtime checks in+ batch exports; see `get_credentials_using_user_aws_role` in+ `s3_batch_export.py`.+ """+ has_same_aws_role_integrations = (+ Integration.objects.select_related("team__organization")+ .filter(+ kind=Integration.IntegrationKind.AWS_S3,+ config__aws_role_arn=aws_role_arn,+ )+ .exclude(team__organization_id=organization_id)+ ).exists()++ if has_same_aws_role_integrations:+ return False++ return True+++def _return_non_empty_str_from_config(config: Mapping, key: str) -> str | None:+ if (value := config.get(key)) is not None and isinstance(value, str) and len(value) > 0:+ return value+ return None+++class AwsS3RoleBasedIntegration:+ """An AWS S3 integration storing a customer's AWS role."""++ integration: Integration+ aws_role_arn: str++ def __init__(self, integration: Integration) -> None:+ if integration.kind != Integration.IntegrationKind.AWS_S3:+ raise S3CredentialIntegrationError(+ f"Integration provided is not an AWS S3 integration (got kind='{integration.kind}')"+ )+ self.integration = integration+ try:+ self.aws_role_arn = integration.config["aws_role_arn"]+ except KeyError:+ raise S3CredentialIntegrationError("S3 integration is not valid: 'aws_role_arn' missing")++ @classmethod+ def integration_from_config(+ cls,+ team_id: int,+ organization_id: str,+ created_by: "User | None" = None,+ **config,+ ) -> Integration:+ name = _return_non_empty_str_from_config(config, "name")+ if not name:+ raise S3CredentialIntegrationError("A name is required for an AWS S3 integration")++ aws_role_arn = _return_non_empty_str_from_config(config, "aws_role_arn")+ if not aws_role_arn:+ raise S3CredentialIntegrationError("A valid role ARN is required for an AWS S3 integration")++ if not is_unique_aws_role_by_organization_id(aws_role_arn, organization_id):+ raise ValidationError("Cannot create AWS S3 integration: Invalid role")++ return _create_unique_s3_integration(+ team_id=team_id,+ kind=Integration.IntegrationKind.AWS_S3,+ name=name,+ config={"name": name, "aws_role_arn": aws_role_arn},+ sensitive_config={},+ created_by=created_by,+ )++class AwsS3Integration:"""An AWS S3 integration storing reusable AWS credentials.@@ -3609,14 +3693,21 @@ class AwsS3Integration:def integration_from_config(cls,team_id: int,- name: str,- aws_access_key_id: str,- aws_secret_access_key: str,created_by: "User | None" = None,+ **config,) -> Integration:+ name = _return_non_empty_str_from_config(config, "name")if not name:raise S3CredentialIntegrationError("A name is required for an AWS S3 integration")+ aws_access_key_id = _return_non_empty_str_from_config(config, "aws_access_key_id")+ if not aws_access_key_id:+ raise S3CredentialIntegrationError("Access key ID is required for an AWS S3 integration")++ aws_secret_access_key = _return_non_empty_str_from_config(config, "aws_secret_access_key")+ if not aws_secret_access_key:+ raise S3CredentialIntegrationError("Secret access key is required for an AWS S3 integration")+# Fail fast on invalid/expired credentials, and capture the (non-sensitive) account id.account_id = cls.validate_credentials(aws_access_key_id, aws_secret_access_key)diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex 38efc017fdc8..76a2aab35a9b 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -2381,8 +2381,8 @@ class TestAwsS3IntegrationModel(BaseTest):"aws_access_key_id": "AKIAEXAMPLE","aws_secret_access_key": "secret",}- # display_name surfaces auth type and AWS account so users can tell integrations apart.- assert integration.display_name == "prod-aws (access key, AWS account 123456789012)"+ # display_name surfaces AWS account so users can tell integrations apart.+ assert integration.display_name == "prod-aws (AWS account 123456789012)"assert AwsS3Integration(integration).aws_account_id == "123456789012"def test_integration_from_config_requires_name(self):diff --git a/posthog/settings/batch_exports.py b/posthog/settings/batch_exports.pyindex a2d577b0c6fa..f5c46ab94441 100644--- a/posthog/settings/batch_exports.py+++ b/posthog/settings/batch_exports.py@@ -8,6 +8,7 @@ BATCH_EXPORT_S3_RECORD_BATCH_QUEUE_MAX_SIZE_BYTES: int = get_from_env("BATCH_EXPORT_S3_RECORD_BATCH_QUEUE_MAX_SIZE_BYTES", 1024 * 1024 * 100, type_cast=int)BATCH_EXPORT_S3_MAX_CONCURRENT_UPLOADS: int = get_from_env("BATCH_EXPORT_S3_MAX_CONCURRENT_UPLOADS", 5, type_cast=int)+BATCH_EXPORT_S3_EXTERNAL_ROLE_ARN: str = get_from_env("BATCH_EXPORT_S3_EXTERNAL_ROLE_ARN", "")BATCH_EXPORT_SNOWFLAKE_UPLOAD_CHUNK_SIZE_BYTES: int = 1024 * 1024 * 100 # 100MBBATCH_EXPORT_SNOWFLAKE_RECORD_BATCH_QUEUE_MAX_SIZE_BYTES: int = get_from_env(diff --git a/products/batch_exports/backend/api/batch_export.py b/products/batch_exports/backend/api/batch_export.pyindex 13f40cb525aa..d6101a6817b7 100644--- a/products/batch_exports/backend/api/batch_export.py+++ b/products/batch_exports/backend/api/batch_export.py@@ -38,14 +38,11 @@ from posthog.api.utils import actionfrom posthog.event_usage import groupsfrom posthog.models import Team, Userfrom posthog.models.integration import (- AwsS3Integration,AzureBlobIntegration,AzureBlobIntegrationError,DatabricksIntegration,DatabricksIntegrationError,Integration,- S3CompatibleIntegration,- S3CredentialIntegrationError,)from posthog.temporal.common.client import sync_connectfrom posthog.utils import relative_date_parse, str_to_bool@@ -610,12 +607,12 @@ class BatchExportRequestSerializer(serializers.Serializer):)-# S3-family destinations that may authenticate via an Integration, mapped to the handler that-# validates the linked integration's kind and credentials. Adding a future S3-family destination-# (e.g. a first-class GCS-via-S3 type) is a one-line addition here.-S3_INTEGRATION_HANDLERS: dict[str, type[AwsS3Integration] | type[S3CompatibleIntegration]] = {- BatchExportDestination.Destination.AWS_S3: AwsS3Integration,- BatchExportDestination.Destination.S3_COMPATIBLE: S3CompatibleIntegration,+# S3-family destinations that may authenticate via an Integration, mapped to+# the linked integration's kind. Adding a future S3-family destination (e.g. a+# first-class GCS-via-S3 type) is a one-line addition here.+S3_DESTINATION_TO_INTEGRATION_KIND: dict[str, Integration.IntegrationKind] = {+ BatchExportDestination.Destination.AWS_S3: Integration.IntegrationKind.AWS_S3,+ BatchExportDestination.Destination.S3_COMPATIBLE: Integration.IntegrationKind.S3_COMPATIBLE,}@@ -1165,12 +1162,15 @@ class BatchExportSerializer(serializers.ModelSerializer):required_non_empty_inputs = ["bucket_name", "region", "prefix"]# Credentials are only required inline when no Integration provides them.if integration is None:- required_non_empty_inputs += ["aws_access_key_id", "aws_secret_access_key"]+ required_non_empty_inputs += ["aws_access_key_id", "aws_secret_access_key", "aws_role_arn"]+empty_inputs = []+for required_input in required_non_empty_inputs:value = config.get(required_input)if value is not None and isinstance(value, str) and value.strip() == "":empty_inputs.append(required_input)+if empty_inputs:raise serializers.ValidationError(f"The following inputs are empty: {empty_inputs}")@@ -1180,15 +1180,18 @@ class BatchExportSerializer(serializers.ModelSerializer):if integration is not None:# An Integration only makes sense for the integration-backed S3 types. Reject it on the# legacy "S3" type- # TODO: remove this branch once the legacy "S3" destination type is fully removed.- if destination_type not in S3_INTEGRATION_HANDLERS:+ # TODO: remove this branch once the legacy "S3" destination type is fully removed+ try:+ kind = S3_DESTINATION_TO_INTEGRATION_KIND[destination_type]+ except KeyError:raise serializers.ValidationError(f"{destination_type} destinations do not support integration-based credentials.")- try:- S3_INTEGRATION_HANDLERS[destination_type](integration)- except S3CredentialIntegrationError as e:- raise serializers.ValidationError(str(e))++ if not integration.kind == kind:+ raise serializers.ValidationError(+ f"Integration provided is not an AWS S3 integration (got kind='{integration.kind}')"+ )# JSONLines is the default file format for S3 exports for legacy reasonsfile_format = merged_config.get("file_format", "JSONLines")diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.pyindex ee7e6d132be4..8797e1ce0740 100644--- a/products/batch_exports/backend/service.py+++ b/products/batch_exports/backend/service.py@@ -399,6 +399,7 @@ IAMRole = strclass AWSCredentials:aws_access_key_id: straws_secret_access_key: str+ aws_session_token: str | None = None@dataclassdiff --git a/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py b/products/batch_exports/backend/temporal/destinations/redshift_batch_export.pyindex d319c8543fe3..c81017f70b64 100644--- a/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py@@ -12,13 +12,13 @@ from django.conf import settingsimport psycopgimport pyarrow as pa-import aioboto3import botocore.exceptionsfrom psycopg import sqlfrom structlog.contextvars import bind_contextvarsfrom temporalio import activity, workflowfrom temporalio.common import RetryPolicy+from posthog.models import Teamfrom posthog.models.integration import TLS, Authority, Credentialsfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.heartbeat import Heartbeater@@ -45,7 +45,13 @@ from products.batch_exports.backend.temporal.destinations.postgres_batch_exportPostgreSQLClient,PostgreSQLField,)-from products.batch_exports.backend.temporal.destinations.s3_batch_export import ConcurrentS3Consumer+from products.batch_exports.backend.temporal.destinations.s3_batch_export import (+ ConcurrentS3Consumer,+ PolicyStatement,+ get_credentials_using_user_aws_role,+ s3_client,+)+from products.batch_exports.backend.temporal.destinations.utils import get_absolute_key_prefixfrom products.batch_exports.backend.temporal.pipeline.consumer import Consumer, run_consumer_from_stagefrom products.batch_exports.backend.temporal.pipeline.entrypoint import execute_batch_export_using_internal_stagefrom products.batch_exports.backend.temporal.pipeline.producer import Producer@@ -625,8 +631,7 @@ def get_redshift_fields_from_record_schema(class S3StageBucketParameters:name: strregion_name: str- # TODO: We should support AWS RBAC in S3 batch export.- credentials: AWSCredentials+ credentials: IAMRole | AWSCredentials@dataclasses.dataclass@@ -1034,11 +1039,9 @@ async def insert_into_redshift_activity_from_stage(inputs: RedshiftInsertInputs)async def upload_manifest_file(bucket: str,region_name: str,- aws_access_key_id: str | None,- aws_secret_access_key: str | None,+ credentials: AWSCredentials,files_uploaded: list[str],manifest_key: str,- endpoint_url: str | None = None,):"""Upload manifest file used by Redshift COPY.@@ -1048,13 +1051,14 @@ async def upload_manifest_file(requirement when using Parquet. Since we don't track exactly the size of bytes ofeach Parquet file produced, this function gets it from S3 instead."""- session = aioboto3.Session()- async with session.client(- "s3",- region_name=region_name,- aws_access_key_id=aws_access_key_id,- aws_secret_access_key=aws_secret_access_key,- endpoint_url=endpoint_url,++ async with s3_client(+ credentials.aws_access_key_id,+ credentials.aws_secret_access_key,+ credentials.aws_session_token,+ region=region_name,+ # Required for unit tests which run against a local bucket, otherwise always None.+ endpoint_url=settings.OBJECT_STORAGE_ENDPOINT if settings.TEST else None,) as client:entries = []@@ -1114,23 +1118,18 @@ async def upload_manifest_file(manifest = {"entries": entries}- optional_kwargs = {}- if endpoint_url is None:- optional_kwargs["ChecksumAlgorithm"] = "CRC64NVME"-await client.put_object(Bucket=bucket,Key=manifest_key,Body=json.dumps(manifest),- **optional_kwargs, # type: ignore+ ChecksumAlgorithm="CRC64NVME",)async def delete_uploaded_files(bucket: str,region_name: str,- aws_access_key_id: str | None,- aws_secret_access_key: str | None,+ credentials: AWSCredentials,files_uploaded: list[str],manifest_key: str,):@@ -1141,12 +1140,11 @@ async def delete_uploaded_files(The delete itself is a "best-effort" as we don't want to fail the batch export ifthis fails."""- session = aioboto3.Session()- async with session.client(- "s3",- region_name=region_name,- aws_access_key_id=aws_access_key_id,- aws_secret_access_key=aws_secret_access_key,+ async with s3_client(+ credentials.aws_access_key_id,+ credentials.aws_secret_access_key,+ credentials.aws_session_token,+ region=region_name,) as client:async def delete_key(f: str):@@ -1178,12 +1176,11 @@ async def is_s3_read_access_denied(original failure just because the probe itself couldn't run."""try:- session = aioboto3.Session()- async with session.client(- "s3",- region_name=region_name,- aws_access_key_id=credentials.aws_access_key_id,- aws_secret_access_key=credentials.aws_secret_access_key,+ async with s3_client(+ credentials.aws_access_key_id,+ credentials.aws_secret_access_key,+ credentials.aws_session_token,+ region=region_name,) as client:for key in keys:try:@@ -1333,22 +1330,39 @@ async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInp# some nice round somewhere in the range (100MB).# TODO: Maybe derive this from user's input?max_file_size_mb = 100- consumer = ConcurrentS3Consumer(- bucket=inputs.copy.s3_bucket.name,- region_name=inputs.copy.s3_bucket.region_name,- prefix=inputs.copy.s3_key_prefix,- data_interval_start=inputs.batch_export.data_interval_start,- data_interval_end=inputs.batch_export.data_interval_end,- batch_export_model=inputs.batch_export.batch_export_model,- file_format="Parquet",- compression="zstd",- encryption=None,- aws_access_key_id=inputs.copy.s3_bucket.credentials.aws_access_key_id,- aws_secret_access_key=inputs.copy.s3_bucket.credentials.aws_secret_access_key,- max_file_size_mb=max_file_size_mb,- part_size=settings.BATCH_EXPORT_S3_UPLOAD_CHUNK_SIZE_BYTES,- max_concurrent_uploads=settings.BATCH_EXPORT_S3_MAX_CONCURRENT_UPLOADS,- )++ if isinstance(inputs.copy.s3_bucket.credentials, IAMRole):+ team = await Team.objects.aget(id=inputs.batch_export.team_id)+ organization_id = str(team.organization_id)++ bucket_name = inputs.copy.s3_bucket.name+ key_prefix = get_absolute_key_prefix(+ inputs.copy.s3_key_prefix,+ inputs.batch_export.data_interval_start,+ inputs.batch_export.data_interval_end,+ inputs.batch_export.batch_export_model,+ )+ policy_statements = [+ PolicyStatement(+ Effect="Allow",+ Action=["s3:PutObject", "s3:GetObject", "s3:DeleteObject", "s3:AbortMultipartUpload"],+ Resource=f"arn:aws:s3:::{bucket_name}{key_prefix}*",+ ),+ PolicyStatement(+ Effect="Allow",+ Action=["s3:ListBucket"],+ Resource=f"arn:aws:s3:::{bucket_name}",+ ),+ ]++ credentials = await get_credentials_using_user_aws_role(+ inputs.copy.s3_bucket.credentials,+ organization_id,+ session_name=f"PostHog-batch-exports-{inputs.batch_export.batch_export_id}",+ policy_statements=policy_statements,+ )+ else:+ credentials = inputs.copy.s3_bucket.credentialstable_schemas = _get_table_schemas(model=model,@@ -1374,14 +1388,36 @@ async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInpelse inputs.table.name)- result = await run_consumer_from_stage(- queue=queue,- consumer=consumer,- producer_task=producer_task,- transformer=transformer,- json_columns=table_schemas.super_columns,- records_total=inputs.batch_export.records_total,- )+ async with s3_client(+ credentials.aws_access_key_id,+ credentials.aws_secret_access_key,+ credentials.aws_session_token,+ region=inputs.copy.s3_bucket.region_name,+ ) as client:+ consumer = ConcurrentS3Consumer(+ bucket=inputs.copy.s3_bucket.name,+ region_name=inputs.copy.s3_bucket.region_name,+ prefix=inputs.copy.s3_key_prefix,+ data_interval_start=inputs.batch_export.data_interval_start,+ data_interval_end=inputs.batch_export.data_interval_end,+ batch_export_model=inputs.batch_export.batch_export_model,+ file_format="Parquet",+ compression="zstd",+ encryption=None,+ s3_client=client,+ max_file_size_mb=max_file_size_mb,+ part_size=settings.BATCH_EXPORT_S3_UPLOAD_CHUNK_SIZE_BYTES,+ max_concurrent_uploads=settings.BATCH_EXPORT_S3_MAX_CONCURRENT_UPLOADS,+ )++ result = await run_consumer_from_stage(+ queue=queue,+ consumer=consumer,+ producer_task=producer_task,+ transformer=transformer,+ json_columns=table_schemas.super_columns,+ records_total=inputs.batch_export.records_total,+ )if result.error is not None:return result@@ -1440,11 +1476,9 @@ async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInpawait upload_manifest_file(bucket=inputs.copy.s3_bucket.name,region_name=inputs.copy.s3_bucket.region_name,- aws_access_key_id=inputs.copy.s3_bucket.credentials.aws_access_key_id,+ credentials=credentials,files_uploaded=consumer.files_uploaded,- aws_secret_access_key=inputs.copy.s3_bucket.credentials.aws_secret_access_key,- # manifest_key is always str, but posixpath.relpath can return both str and bytes.- manifest_key=manifest_key if isinstance(manifest_key, str) else manifest_key.decode("utf-8"),+ manifest_key=manifest_key,)try:@@ -1491,11 +1525,9 @@ async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInpawait delete_uploaded_files(bucket=inputs.copy.s3_bucket.name,region_name=inputs.copy.s3_bucket.region_name,- aws_access_key_id=inputs.copy.s3_bucket.credentials.aws_access_key_id,+ credentials=credentials,files_uploaded=consumer.files_uploaded,- aws_secret_access_key=inputs.copy.s3_bucket.credentials.aws_secret_access_key,- # manifest_key is always str, but posixpath.relpath can return both str and bytes.- manifest_key=manifest_key if isinstance(manifest_key, str) else manifest_key.decode("utf-8"),+ manifest_key=manifest_key,)return resultdiff --git a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py b/products/batch_exports/backend/temporal/destinations/s3_batch_export.pyindex 5cdf173abbd7..bc0d2167e191 100644--- a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/s3_batch_export.py@@ -1,14 +1,16 @@import jsonimport typingimport asyncio+import secretsimport datetime as dt+import contextlibimport dataclasses+import collections.abcimport pyarrow as paimport aioboto3import botocore.exceptionsfrom aiobotocore.config import AioConfig-from aiobotocore.session import ClientCreatorContextfrom opentelemetry import traceif typing.TYPE_CHECKING:@@ -23,15 +25,18 @@ from temporalio.common import RetryPolicyfrom posthog.models.integration import (AwsS3Integration,+ AwsS3RoleBasedIntegration,Integration,S3CompatibleIntegration,S3CredentialIntegrationError,)+from posthog.models.team import Teamfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.logger import get_logger, get_write_only_loggerfrom products.batch_exports.backend.service import (+ AWSCredentials,BatchExportField,BatchExportInsertInputs,BatchExportModel,@@ -47,7 +52,11 @@ from products.batch_exports.backend.temporal.batch_exports import (from products.batch_exports.backend.temporal.destinations.constants import (S3_SUPPORTED_COMPRESSIONS as SUPPORTED_COMPRESSIONS,)-from products.batch_exports.backend.temporal.destinations.utils import get_manifest_key, get_object_key+from products.batch_exports.backend.temporal.destinations.utils import (+ get_absolute_key_prefix,+ get_manifest_key,+ get_object_key,+)from products.batch_exports.backend.temporal.metrics import Attributes, CumulativeTimer, ExecutionTimeRecorderfrom products.batch_exports.backend.temporal.pipeline.consumer import Consumer, run_consumer_from_stagefrom products.batch_exports.backend.temporal.pipeline.entrypoint import execute_batch_export_using_internal_stage@@ -101,6 +110,7 @@ COMPRESSION_EXTENSIONS = {LOGGER = get_write_only_logger(__name__)EXTERNAL_LOGGER = get_logger("EXTERNAL")TRACER = trace.get_tracer(__name__)+SESSION = aioboto3.Session()class UnsupportedFileFormatError(Exception):@@ -124,7 +134,9 @@ class S3IntegrationNotFoundError(Exception):super().__init__(f"S3 integration with ID '{integration_id}' not found for team '{team_id}'")-async def _get_s3_integration(integration_id: int, team_id: int) -> AwsS3Integration | S3CompatibleIntegration:+async def _get_s3_integration(+ integration_id: int, team_id: int+) -> AwsS3RoleBasedIntegration | AwsS3Integration | S3CompatibleIntegration:"""Fetch an S3-family integration from the database.The kind is validated on create by the batch export serializer, so the wrong-kind branch is@@ -138,9 +150,13 @@ async def _get_s3_integration(integration_id: int, team_id: int) -> AwsS3Integraraise S3IntegrationNotFoundError(integration_id, team_id)if integration.kind == Integration.IntegrationKind.AWS_S3:+ if "aws_role_arn" in integration.config:+ return AwsS3RoleBasedIntegration(integration)return AwsS3Integration(integration)+if integration.kind == Integration.IntegrationKind.S3_COMPATIBLE:return S3CompatibleIntegration(integration)+raise S3CredentialIntegrationError(f"Integration with ID '{integration_id}' for team '{team_id}' is not an S3 integration "f"(kind='{integration.kind}')"@@ -348,6 +364,170 @@ class S3BatchExportResult(BatchExportResult):files_uploaded: list[str] = dataclasses.field(default_factory=list)+class PolicyStatement(typing.TypedDict):+ Effect: typing.Literal["Allow", "Deny"]+ Action: list[str]+ Resource: str+++async def get_credentials_using_user_aws_role(+ aws_role_arn: str,+ external_id: str,+ /,+ session_name: str,+ policy_statements: list[PolicyStatement],+ duration: int = 3600,+ max_attempts: int = 5,+ delay: int | float = 1.0,+) -> AWSCredentials:+ """Attempt to obtain credentials assuming a user-provided AWS role.++ This assumes the pre-configured external AWS role available as the+ BATCH_EXPORT_S3_EXTERNAL_ROLE_ARN setting is provided to users upon setting+ up an AWS S3 integration.++ Then, we use credentials from the external AWS role to assume the role+ provided by our users, finally returning our users credentials.++ Arguments:+ aws_role_arn: User-provided AWS role ARN. Should have S3 access+ permissions required for batch exports.+ external_id: An additional ID provided to users for security.+ session_name: The name used for both AWS sessions.+ policy_statements: Policy statements to request narrower permissions on+ final assumed role.+ duration: Maximum session duration, in seconds (1 hour limit).+ max_attempts: How many times to attempt to connect. Useful for tests as+ roles and/or policies may not be immediately available.+ delay: Initial delay in between connection attempts.+ """+ for attempt in range(1, max_attempts + 1):+ try:+ async with SESSION.client("sts") as sts:+ first_response = await sts.assume_role(+ RoleArn=settings.BATCH_EXPORT_S3_EXTERNAL_ROLE_ARN,+ RoleSessionName=session_name,+ # Hard limit of 1h imposed by AWS+ # TODO: Support refreshable credentials so we can support batch+ # exports running for longer+ DurationSeconds=duration,+ Policy=json.dumps(+ # Narrow permissions to only allow assuming provided role with this+ # session.+ {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Action": ["sts:AssumeRole"],+ "Resource": aws_role_arn,+ },+ ],+ }+ ),+ )++ except botocore.exceptions.ClientError as e:+ code = e.response["Error"]["Code"]+ if code not in ("AccessDenied", "InvalidClientTokenId") or attempt == max_attempts:+ raise++ await asyncio.sleep(min(delay * (2**attempt), 32))+ continue++ external_session = aioboto3.Session(+ aws_access_key_id=first_response["Credentials"]["AccessKeyId"],+ aws_secret_access_key=first_response["Credentials"]["SecretAccessKey"],+ aws_session_token=first_response["Credentials"]["SessionToken"],+ )+ try:+ async with external_session.client("sts") as sts:+ try:+ # This first call is expected to fail, as it includes an+ # invalid ExternalId. Passing here would indicate the+ # customer has not included ExternalId condition in their+ # policy, and we should fail.+ _ = await sts.assume_role(+ RoleArn=aws_role_arn,+ RoleSessionName=session_name,+ DurationSeconds=duration,+ ExternalId=secrets.token_hex(67),+ )+ except Exception:+ pass+ else:+ raise InvalidCredentialsError(+ f"The provided role '{aws_role_arn}' allows access without a required external id condition. Update the role's policy with a condition to match '{external_id}' as a external id."+ )+ second_response = await sts.assume_role(+ RoleArn=aws_role_arn,+ RoleSessionName=session_name,+ DurationSeconds=duration,+ ExternalId=external_id,+ Policy=json.dumps(+ # Narrow permissions in this session.+ {+ "Version": "2012-10-17",+ "Statement": policy_statements,+ }+ ),+ )++ except botocore.exceptions.ClientError as e:+ code = e.response["Error"]["Code"]+ if code not in ("AccessDenied", "InvalidClientTokenId") or attempt == max_attempts:+ raise++ await asyncio.sleep(min(delay * (2**attempt), 32))+ continue+ else:+ break++ return AWSCredentials(+ aws_access_key_id=second_response["Credentials"]["AccessKeyId"],+ aws_secret_access_key=second_response["Credentials"]["SecretAccessKey"],+ aws_session_token=second_response["Credentials"]["SessionToken"],+ )+++async def s3_client(+ aws_access_key_id: str,+ aws_secret_access_key: str,+ aws_session_token: str | None,+ region: str,+ use_virtual_style_addressing: bool = False,+ endpoint_url: str | None = None,+) -> collections.abc.AsyncIterator["S3Client"]:+ session = aioboto3.Session(+ aws_access_key_id=aws_access_key_id,+ aws_secret_access_key=aws_secret_access_key,+ aws_session_token=aws_session_token,+ )++ config: dict[str, typing.Any] = {+ # Increase connection pool, so to ensure we're not limited by this+ "max_pool_connections": settings.BATCH_EXPORT_S3_MAX_CONCURRENT_UPLOADS * 5,+ # Set checksum calculation to 'when_required' for compatibility with S3-compatible+ # services like GCS that don't support AWS's newer checksum features+ "request_checksum_calculation": "when_required",+ "response_checksum_validation": "when_required",+ }+ if use_virtual_style_addressing:+ config["s3"] = {"addressing_style": "virtual"}++ try:+ async with session.client(+ "s3", config=AioConfig(**config), region_name=region, endpoint_url=endpoint_url+ ) as s3_client:+ yield s3_client++ except ValueError as err:+ if "Invalid endpoint" in str(err):+ raise InvalidS3EndpointError(str(err)) from err+ raise++@activity.defn@handle_non_retryable_errors(NON_RETRYABLE_ERROR_TYPES)async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> S3BatchExportResult:@@ -371,33 +551,102 @@ async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> S3BatchEdata_interval_end=inputs.data_interval_end,)- # Integration-backed exports resolve credentials at run time; legacy exports carry them inline.- # TODO: require integration- if inputs.integration_id is not None:- integration = await _get_s3_integration(inputs.integration_id, inputs.team_id)- inputs.aws_access_key_id = integration.aws_access_key_id- inputs.aws_secret_access_key = integration.aws_secret_access_key- if isinstance(integration, S3CompatibleIntegration):- inputs.endpoint_url = integration.endpoint_url-if inputs.file_format not in FILE_FORMAT_EXTENSIONS:raise UnsupportedFileFormatError(inputs.file_format)if inputs.compression is not None and inputs.compression not in SUPPORTED_COMPRESSIONS[inputs.file_format]:raise UnsupportedCompressionError(inputs.compression)- external_logger = EXTERNAL_LOGGER.bind()+ async with Heartbeater():+ # Integration-backed exports resolve credentials at run time; legacy exports carry them inline.+ # TODO: require integration+ aws_access_key_id = inputs.aws_access_key_id+ aws_secret_access_key = inputs.aws_secret_access_key+ aws_session_token = inputs.aws_session_token+ endpoint_url = inputs.endpoint_url++ if inputs.integration_id is not None:+ integration = await _get_s3_integration(inputs.integration_id, inputs.team_id)++ if isinstance(integration, AwsS3Integration):+ aws_access_key_id = integration.aws_access_key_id+ aws_secret_access_key = integration.aws_secret_access_key++ if isinstance(integration, AwsS3RoleBasedIntegration):+ team = await Team.objects.aget(id=inputs.team_id)+ organization_id = str(team.organization_id)++ bucket_name = inputs.bucket_name+ key_prefix = get_absolute_key_prefix(+ inputs.prefix, inputs.data_interval_start, inputs.data_interval_end, inputs.batch_export_model+ )++ policy_statements = [+ PolicyStatement(+ Effect="Allow",+ Action=["s3:PutObject", "s3:AbortMultipartUpload"],+ Resource=f"arn:aws:s3:::{bucket_name}{key_prefix}*",+ )+ ]++ # TODO: We should be more explicit about this parameter being+ # an ARN or an ID+ if inputs.kms_key_id is not None:+ # KMS key could be in a different acount, in which case+ # a customer would have provided the full ARN here.+ if inputs.kms_key_id.startswith("arn:"):+ resource = inputs.kms_key_id++ else:+ # If not, assume that the KMS key is in the same account as the role+ # we are assuming. This is the same assumption S3 makes when passing+ # just a key ID.+ parts = integration.aws_role_arn.split(":")+ if len(parts) < 6 or not parts[4]:+ raise ValueError(f"Malformed role ARN: {integration.aws_role_arn!r}")+ account_id = parts[4]++ # I am aware KMS key aliases are a thing, but we explicitly ask for+ # KMS key "ID". It's a user error if they pass an alias (and we can)+ # just tell them to use the full ARN then.+ resource = f"arn:aws:kms:{inputs.region}:{account_id}:key/{inputs.kms_key_id}"++ policy_statements.append(+ PolicyStatement(+ Effect="Allow",+ Action=["kms:GenerateDataKey", "kms:Decrypt"],+ Resource=resource,+ )+ )++ credentials = await get_credentials_using_user_aws_role(+ integration.aws_role_arn,+ organization_id,+ session_name=f"PostHog-batch-exports-{inputs.batch_export_id}",+ policy_statements=policy_statements,+ )+ aws_access_key_id, aws_secret_access_key, aws_session_token = (+ credentials.aws_access_key_id,+ credentials.aws_secret_access_key,+ credentials.aws_session_token,+ )- external_logger.info(- "Batch exporting range %s - %s to S3: %s",- inputs.data_interval_start or "START",- inputs.data_interval_end or "END",- get_s3_key_from_inputs(inputs),- )+ if isinstance(integration, S3CompatibleIntegration):+ aws_access_key_id = integration.aws_access_key_id+ aws_secret_access_key = integration.aws_secret_access_key+ endpoint_url = integration.endpoint_url- async with Heartbeater():- # NOTE: we don't support resuming from heartbeats for this activity for 2 reasons:- # - resuming from old heartbeats doesn't play nicely with S3 multipart uploads- # - we don't order the events in the query to ClickHouse+ if not aws_access_key_id or not aws_secret_access_key:+ # At these point these need to be defined: either by us assuming a new+ # role, by an integration, or by the inputs.+ raise InvalidCredentialsError("AWS access key ID and secret access key cannot be empty")++ external_logger = EXTERNAL_LOGGER.bind()+ external_logger.info(+ "Batch exporting range %s - %s to S3: %s",+ inputs.data_interval_start or "START",+ inputs.data_interval_end or "END",+ get_s3_key_from_inputs(inputs),+ )queue = RecordBatchQueue(max_size_bytes=settings.BATCH_EXPORT_S3_RECORD_BATCH_QUEUE_MAX_SIZE_BYTES)producer = ProducerFromInternalStage()@@ -430,12 +679,6 @@ async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> S3BatchE[field.with_nullable(True) for field in record_batch_schema])- consumer = ConcurrentS3Consumer.from_inputs(- s3_inputs=inputs,- part_size=settings.BATCH_EXPORT_S3_UPLOAD_CHUNK_SIZE_BYTES,- max_concurrent_uploads=settings.BATCH_EXPORT_S3_MAX_CONCURRENT_UPLOADS,- )-json_columns = ("properties", "person_properties", "set", "set_once")if inputs.file_format.lower() == "jsonlines":transformer = get_json_stream_transformer(@@ -450,14 +693,30 @@ async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> S3BatchEmax_file_size_bytes=inputs.max_file_size_mb * 1024 * 1024 if inputs.max_file_size_mb else 0,)- result = await run_consumer_from_stage(- queue=queue,- consumer=consumer,- producer_task=producer_task,- transformer=transformer,- json_columns=json_columns,- records_total=inputs.records_total,- )+ async with s3_client(+ aws_access_key_id,+ aws_secret_access_key,+ aws_session_token,+ use_virtual_style_addressing=inputs.use_virtual_style_addressing,+ region=inputs.region,+ endpoint_url=endpoint_url,+ ) as client:+ consumer = ConcurrentS3Consumer.from_inputs(+ s3_client=client,+ s3_inputs=inputs,+ part_size=settings.BATCH_EXPORT_S3_UPLOAD_CHUNK_SIZE_BYTES,+ max_concurrent_uploads=settings.BATCH_EXPORT_S3_MAX_CONCURRENT_UPLOADS,+ )++ result = await run_consumer_from_stage(+ queue=queue,+ consumer=consumer,+ producer_task=producer_task,+ transformer=transformer,+ json_columns=json_columns,+ records_total=inputs.records_total,+ )+return S3BatchExportResult(bytes_exported=result.bytes_exported,records_completed=result.records_completed,@@ -481,6 +740,7 @@ class ConcurrentS3Consumer(Consumer):def __init__(self,+ s3_client: "S3Client",bucket: str,region_name: str,prefix: str,@@ -488,9 +748,6 @@ class ConcurrentS3Consumer(Consumer):data_interval_end: str,batch_export_model: BatchExportModel | None,file_format: str,- aws_access_key_id: str,- aws_secret_access_key: str,- aws_session_token: str | None = None,kms_key_id: str | None = None,max_file_size_mb: int | None = None,compression: str | None = None,@@ -502,11 +759,6 @@ class ConcurrentS3Consumer(Consumer):):super().__init__(model=batch_export_model.name if batch_export_model else "events")- if (isinstance(aws_access_key_id, str) and aws_access_key_id.strip() == "") or (- isinstance(aws_secret_access_key, str) and aws_secret_access_key.strip() == ""- ):- raise InvalidCredentialsError("AWS access key ID and secret access key cannot be empty")-self.bucket = bucketself.region_name = region_nameself.prefix = prefix@@ -523,9 +775,6 @@ class ConcurrentS3Consumer(Consumer):# TODO: Remove this from here, figure out a different way to obtain an S3 key.self.max_file_size_mb = max_file_size_mb- self.aws_access_key_id = aws_access_key_id- self.aws_secret_access_key = aws_secret_access_key- self.aws_session_token = aws_session_tokenself.kms_key_id = kms_key_idself.endpoint_url = endpoint_urlself.use_virtual_style_addressing = use_virtual_style_addressing@@ -537,10 +786,7 @@ class ConcurrentS3Consumer(Consumer):# already in flight), reported as a span attribute. When this dominates the consumer's# consume time, the bottleneck is upload throughput to the destination.self._upload_slot_wait_timer = CumulativeTimer()-- self._session = aioboto3.Session()- self._s3_client: S3Client | None = None # Shared S3 client- self._s3_client_ctx: ClientCreatorContext[S3Client] | None = None # Context manager for cleanup+ self.s3_client = s3_client# File splitting managementself.current_file_index = 0@@ -558,14 +804,13 @@ class ConcurrentS3Consumer(Consumer):@classmethoddef from_inputs(cls,+ s3_client: "S3Client",s3_inputs: S3InsertInputs,part_size: int = 50 * 1024 * 1024,max_concurrent_uploads: int = 5,):- if not s3_inputs.aws_access_key_id or not s3_inputs.aws_secret_access_key:- raise InvalidCredentialsError()-return cls(+ s3_client=s3_client,bucket=s3_inputs.bucket_name,region_name=s3_inputs.region,prefix=s3_inputs.prefix,@@ -576,9 +821,6 @@ class ConcurrentS3Consumer(Consumer):compression=s3_inputs.compression,encryption=s3_inputs.encryption,max_file_size_mb=s3_inputs.max_file_size_mb,- aws_access_key_id=s3_inputs.aws_access_key_id,- aws_secret_access_key=s3_inputs.aws_secret_access_key,- aws_session_token=s3_inputs.aws_session_token,kms_key_id=s3_inputs.kms_key_id,endpoint_url=s3_inputs.endpoint_url,use_virtual_style_addressing=s3_inputs.use_virtual_style_addressing,@@ -586,43 +828,6 @@ class ConcurrentS3Consumer(Consumer):max_concurrent_uploads=max_concurrent_uploads,)- async def _get_s3_client(self) -> "S3Client":- """Get or create the shared S3 client.-- It significantly improves performance to share a single S3 client across all uploads.- """- if self._s3_client is None:- config: dict[str, typing.Any] = {- "max_pool_connections": self.max_concurrent_uploads- * 5, # Increase connection pool, so to ensure we're not limited by this- # Set checksum calculation to 'when_required' for compatibility with S3-compatible- # services like GCS that don't support AWS's newer checksum features- "request_checksum_calculation": "when_required",- "response_checksum_validation": "when_required",- }- if self.use_virtual_style_addressing:- config["s3"] = {"addressing_style": "virtual"}- boto_config = AioConfig(**config)-- try:- client_ctx = self._session.client(- "s3",- region_name=self.region_name,- aws_access_key_id=self.aws_access_key_id,- aws_secret_access_key=self.aws_secret_access_key,- aws_session_token=self.aws_session_token,- endpoint_url=self.endpoint_url,- config=boto_config,- )- self._s3_client = await client_ctx.__aenter__()- # Store the context manager for proper cleanup- self._s3_client_ctx = client_ctx- except ValueError as err:- if "Invalid endpoint" in str(err):- raise InvalidS3EndpointError(str(err)) from err- raise- return self._s3_client-async def finalize_file(self):await self._finalize_current_file()await self._start_new_file()@@ -717,8 +922,6 @@ class ConcurrentS3Consumer(Consumer):self.upload_id,)current_key = self._get_current_key()- client = self._s3_client- assert client is not None, "No S3 client, is multi-part initialized?"# Retry logic for upload_partresponse: UploadPartOutputTypeDef | None = None@@ -755,7 +958,7 @@ class ConcurrentS3Consumer(Consumer):while response is None:attempt += 1try:- response = await client.upload_part(+ response = await self.s3_client.upload_part(Bucket=self.bucket,Key=current_key,PartNumber=part_number,@@ -903,12 +1106,11 @@ class ConcurrentS3Consumer(Consumer):optional_kwargs["ChecksumAlgorithm"] = "CRC64NVME"current_key = self._get_current_key()- client = await self._get_s3_client()with TRACER.start_as_current_span("batch_export.s3.create_multipart_upload",attributes={"batch_export.s3.file_number": self.current_file_index},):- response = await client.create_multipart_upload(+ response = await self.s3_client.create_multipart_upload(Bucket=self.bucket,Key=current_key,**optional_kwargs, # type: ignore@@ -929,15 +1131,11 @@ class ConcurrentS3Consumer(Consumer):# Cleanup on errorawait self._abort()raise+finally:self._finalized = True# Final cleanupself.current_buffer.clear()- # Close the shared S3 client- if self._s3_client is not None and self._s3_client_ctx is not None:- await self._s3_client_ctx.__aexit__(None, None, None)- self._s3_client = None- self._s3_client_ctx = None# If using max file size (and therefore potentially expecting more than one file) upload a manifest file# containing the list of files. This is used to check if the export is complete.@@ -957,25 +1155,18 @@ class ConcurrentS3Consumer(Consumer):files_uploaded: list[str],manifest_key: str,):- client = await self._get_s3_client()-optional_kwargs = {}if self.endpoint_url is None:optional_kwargs["ChecksumAlgorithm"] = "CRC64NVME"with TRACER.start_as_current_span("batch_export.s3.upload_manifest"):- await client.put_object(+ await self.s3_client.put_object(Bucket=self.bucket,Key=manifest_key,Body=json.dumps({"files": files_uploaded}),**optional_kwargs, # type: ignore)- if self._s3_client is not None and self._s3_client_ctx is not None:- await self._s3_client_ctx.__aexit__(None, None, None)- self._s3_client = None- self._s3_client_ctx = None-# TODO - maybe we can support upload small files without the need for multipart uploads# we just want to ensure we test both versions of the code path# async def _single_file_upload(self):@@ -995,7 +1186,6 @@ class ConcurrentS3Consumer(Consumer):sorted_parts = [self.completed_parts[part_num] for part_num in sorted(self.completed_parts.keys())]current_key = self._get_current_key()- client = await self._get_s3_client()with TRACER.start_as_current_span("batch_export.s3.complete_multipart_upload",attributes={@@ -1003,7 +1193,7 @@ class ConcurrentS3Consumer(Consumer):"batch_export.s3.num_parts": len(sorted_parts),},):- await client.complete_multipart_upload(+ await self.s3_client.complete_multipart_upload(Bucket=self.bucket,Key=current_key,UploadId=self.upload_id,@@ -1021,8 +1211,9 @@ class ConcurrentS3Consumer(Consumer):if self.upload_id:upload_id = self.upload_idtry:- client = await self._get_s3_client()- await client.abort_multipart_upload(Bucket=self.bucket, Key=self._get_current_key(), UploadId=upload_id)+ await self.s3_client.abort_multipart_upload(+ Bucket=self.bucket, Key=self._get_current_key(), UploadId=upload_id+ )except Exception:self.logger.exception("Best-effort abort of multipart upload %s failed", upload_id)finally:diff --git a/products/batch_exports/backend/temporal/destinations/utils.py b/products/batch_exports/backend/temporal/destinations/utils.pyindex 524e566f8974..b1e6848a601d 100644--- a/products/batch_exports/backend/temporal/destinations/utils.py+++ b/products/batch_exports/backend/temporal/destinations/utils.py@@ -42,6 +42,21 @@ def get_key_prefix(return prefix+def get_absolute_key_prefix(+ prefix: str, data_interval_start: str | None, data_interval_end: str, batch_export_model: BatchExportModel | None+) -> str:+ """Like `get_key_prefix`, but ensure key is absolute and ends on a slash."""+ key_prefix = get_key_prefix(prefix, data_interval_start, data_interval_end, batch_export_model)++ # Empty string becomes "/", prefixes without a leading "/" get one,+ # and for everything else this is a no-op.+ key_prefix = posixpath.join("/", key_prefix)+ # Ensures a trailing slash, as all of our object keys join on the prefix,+ # which means they end up after a slash.+ key_prefix = posixpath.join(key_prefix, "")+ return key_prefix++def get_manifest_key(prefix: str, data_interval_start: str | None, data_interval_end: str, batch_export_model: BatchExportModel | None) -> str:diff --git a/products/batch_exports/backend/tests/temporal/README.md b/products/batch_exports/backend/tests/temporal/README.mdindex c12cd206466b..ca5d4643bd18 100644--- a/products/batch_exports/backend/tests/temporal/README.md+++ b/products/batch_exports/backend/tests/temporal/README.md@@ -71,9 +71,9 @@ DEBUG=1 AWS_ACCESS_KEY_ID="AAAA" AWS_SECRET_ACCESS_KEY="BBBB" AWS_REGION="region## Testing S3 batch exports-S3 batch exports are tested against a MinIO bucket available in the local development stack. However there are also unit tests that specifically target an S3 bucket (like `test_s3_export_workflow_with_s3_bucket`) and a Google Cloud Storage (GCS) bucket.+S3 batch exports are tested against a MinIO bucket available in the local development stack. However there are also unit tests that specifically target an S3 bucket (like `test_s3_export_workflow_with_s3_bucket`), tests that target a Google Cloud Storage (GCS) bucket, and tests that run against a playground AWS account.-If no environment variables are defined, then just the tests targeting MinIO will be run (the tests targeting S3/GCS will be skipped).+If no environment variables are defined and no AWS credentials are present, then just the tests targeting MinIO will be run (the tests targeting S3/GCS will be skipped).### Using an S3 bucket@@ -116,6 +116,17 @@ DEBUG=1 GCS_TEST_BUCKET='your-test-bucket' AWS_ACCESS_KEY_ID="AAAA" AWS_SECRET_AReplace the environment variables with the values obtained from the setup steps.+### Using an AWS playground account++Tests in `test_activity_with_role_assumption` require an AWS playground account to run. The good news is that once we are logged in to the AWS playground account, no additional setup is required. The test suite is configured to setup every AWS resource required.++Any AWS account can be a playground account, but the account used must allow chained role assumption (or rather, not block it).++> [!NOTE]+> For PostHog employees, an AWS playground account is available for you.++After acquiring an AWS account, simply log in to it and run the tests like normal. No special environment variables are required. Tests clean-up after themselves once done.+## Testing Snowflake batch exportsSnowflake batch exports are tested against a real Snowflake instance, with additional setup steps required. Due to this requirement, these tests are skipped unless Snowflake credentials are specified in the environment.diff --git a/products/batch_exports/backend/tests/temporal/destinations/redshift/test_redshift_utils.py b/products/batch_exports/backend/tests/temporal/destinations/redshift/test_redshift_utils.pyindex 14d513b9355b..d47fb3f24d4e 100644--- a/products/batch_exports/backend/tests/temporal/destinations/redshift/test_redshift_utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/redshift/test_redshift_utils.py@@ -90,14 +90,20 @@ async def test_upload_manifest_file(minio_client, bucket_name):files_uploaded.append(key)manifest_key = f"/{test_prefix}/manifest.json"++ # Needed for the noisy type checker+ assert settings.OBJECT_STORAGE_ACCESS_KEY_ID is not None+ assert settings.OBJECT_STORAGE_SECRET_ACCESS_KEY is not None+await upload_manifest_file(bucket=bucket_name,region_name="us-east-1",- aws_access_key_id=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- aws_secret_access_key=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,+ credentials=AWSCredentials(+ aws_access_key_id=settings.OBJECT_STORAGE_ACCESS_KEY_ID,+ aws_secret_access_key=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,+ ),files_uploaded=files_uploaded,manifest_key=manifest_key,- endpoint_url=settings.OBJECT_STORAGE_ENDPOINT,)obj = await minio_client.get_object(Bucket=bucket_name, Key=manifest_key)@@ -133,20 +139,23 @@ async def test_upload_manifest_file_raises_on_client_error(minio_client, bucket_mock_session_instance = mock.MagicMock()mock_session_instance.client.return_value = mock_context_manager- with mock.patch(- "products.batch_exports.backend.temporal.destinations.redshift_batch_export.aioboto3.Session"- ) as mock_session_class:+ # Needed for the noisy type checker+ assert settings.OBJECT_STORAGE_ACCESS_KEY_ID is not None+ assert settings.OBJECT_STORAGE_SECRET_ACCESS_KEY is not None++ with mock.patch("aioboto3.Session") as mock_session_class:mock_session_class.return_value = mock_session_instancewith pytest.raises(ClientErrorGroup) as exc_info:await upload_manifest_file(bucket=bucket_name,region_name="us-east-1",- aws_access_key_id=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- aws_secret_access_key=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,+ credentials=AWSCredentials(+ aws_access_key_id=settings.OBJECT_STORAGE_ACCESS_KEY_ID,+ aws_secret_access_key=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,+ ),files_uploaded=files_uploaded,manifest_key=manifest_key,- endpoint_url=settings.OBJECT_STORAGE_ENDPOINT,)assert all(isinstance(exc, botocore.exceptions.ClientError) for exc in exc_info.value.exceptions)assert exc_info.value.ops == {"list_objects_v2": {"AccessDenied"}} # type: ignore@@ -184,9 +193,7 @@ async def test_is_s3_read_access_denied(error_code, status_code, expected):response: Any = {"Error": {"Code": error_code}, "ResponseMetadata": {"HTTPStatusCode": status_code}}head_object = mock.AsyncMock(side_effect=botocore.exceptions.ClientError(response, "HeadObject"))- with mock.patch(- "products.batch_exports.backend.temporal.destinations.redshift_batch_export.aioboto3.Session"- ) as mock_session_class:+ with mock.patch("aioboto3.Session") as mock_session_class:mock_session_class.return_value = _mock_s3_session_with_head_object(head_object)denied = await is_s3_read_access_denied(@@ -203,9 +210,7 @@ async def test_is_s3_read_access_denied_swallows_unexpected_error():"""An unexpected probe failure (e.g. a connection error) is treated as 'not confirmed' (False)."""head_object = mock.AsyncMock(side_effect=botocore.exceptions.EndpointConnectionError(endpoint_url="https://s3"))- with mock.patch(- "products.batch_exports.backend.temporal.destinations.redshift_batch_export.aioboto3.Session"- ) as mock_session_class:+ with mock.patch("aioboto3.Session") as mock_session_class:mock_session_class.return_value = _mock_s3_session_with_head_object(head_object)denied = await is_s3_read_access_denied(diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/conftest.py b/products/batch_exports/backend/tests/temporal/destinations/s3/conftest.pyindex 281fa5924b97..672e8731a656 100644--- a/products/batch_exports/backend/tests/temporal/destinations/s3/conftest.py+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/conftest.py@@ -1,18 +1,39 @@+import os+import jsonimport uuid+import typing+import asyncio+import secrets+import contextlib+import collections.abcimport pytestfrom django.conf import settings+import aioboto3+import structlogimport pytest_asyncio+import botocore.exceptionsfrom posthog.temporal.tests.utils.models import acreate_batch_export, adelete_batch_exportfrom products.batch_exports.backend.tests.temporal.utils.s3 import create_test_client, delete_all_from_s3+if typing.TYPE_CHECKING:+ from types_aiobotocore_s3 import S3Client+pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]+LOGGER = structlog.get_logger()TEST_ROOT_BUCKET = "test-batch-exports"+ARN = str+TEST_REGION = os.getenv("TEST_S3_BUCKET_REGION", "us-east-1")++[email protected](scope="module")+def region() -> str:+ return TEST_REGION@pytest.fixture@@ -133,3 +154,334 @@ async def s3_compatible_batch_export(yield batch_exportawait adelete_batch_export(batch_export, temporal_client)+++@pytest_asyncio.fixture(scope="module")+async def session() -> aioboto3.Session:+ session = aioboto3.Session()++ try:+ async with session.client("sts") as sts:+ await sts.get_caller_identity()+ except (+ botocore.exceptions.NoCredentialsError,+ botocore.exceptions.PartialCredentialsError,+ botocore.exceptions.ClientError,+ botocore.exceptions.NoRegionError,+ ):+ raise pytest.skip("Missing AWS credentials")++ return session+++@pytest_asyncio.fixture(scope="module")+async def kms_key(session: aioboto3.Session) -> collections.abc.AsyncIterator[dict]:+ try:+ async with session.client("kms") as kms:+ resp = await kms.create_key(+ Description="PostHog batch exports test key",+ KeyUsage="ENCRYPT_DECRYPT",+ KeySpec="SYMMETRIC_DEFAULT",+ )+ key_id = resp["KeyMetadata"]["KeyId"]+ yield resp["KeyMetadata"]+ await kms.schedule_key_deletion(+ KeyId=key_id,+ PendingWindowInDays=7, # Minimum+ )++ except (+ botocore.exceptions.NoCredentialsError,+ botocore.exceptions.PartialCredentialsError,+ botocore.exceptions.ClientError,+ botocore.exceptions.NoRegionError,+ ):+ raise pytest.skip("Could not create KMS key")++[email protected](scope="module")+def kms_key_id(kms_key: dict) -> str:+ return kms_key["KeyId"]++[email protected](scope="module")+def kms_key_arn(kms_key: dict) -> str:+ return kms_key["Arn"]+++@pytest_asyncio.fixture(scope="module")+async def s3_client(session: aioboto3.Session) -> collections.abc.AsyncIterator["S3Client"]:+ """Manage an S3 client to interact with an S3 bucket.++ Yields the client after assuming the test bucket exists. Upon resuming, we delete+ the contents of the bucket under the key prefix we are testing.+ """+ async with session.client("s3") as s3_client:+ yield s3_client+++@pytest_asyncio.fixture(scope="module")+async def s3_bucket(bucket_name: str, s3_client: "S3Client", region: str):+ try:+ _ = await s3_client.create_bucket(+ Bucket=bucket_name,+ ACL="private",+ )+ except (+ botocore.exceptions.NoCredentialsError,+ botocore.exceptions.PartialCredentialsError,+ botocore.exceptions.ClientError,+ ):+ raise pytest.skip("Could not setup S3 bucket")++ yield bucket_name++ try:+ await delete_all_from_s3(s3_client, bucket_name, key_prefix="batch-exports")+ await s3_client.delete_bucket(Bucket=bucket_name)+ except Exception:+ LOGGER.warning("Bucket clean-up failed", name=bucket_name, exc_info=True)+++@pytest_asyncio.fixture(scope="module")+async def account_id(session) -> str:+ async with session.client("sts") as sts:+ try:+ identity = await sts.get_caller_identity()+ except (+ botocore.exceptions.NoCredentialsError,+ botocore.exceptions.PartialCredentialsError,+ botocore.exceptions.ClientError,+ ):+ raise pytest.skip("Could not obtain current identity")++ return identity["Account"]+++@pytest_asyncio.fixture(scope="module")+async def identity_role(session) -> str:+ async with session.client("sts") as sts:+ try:+ identity = await sts.get_caller_identity()+ identity_role_name = identity["Arn"].split("/")[-2]+ except (+ botocore.exceptions.NoCredentialsError,+ botocore.exceptions.PartialCredentialsError,+ botocore.exceptions.ClientError,+ ):+ raise pytest.skip("Could not obtain current identity")++ return identity_role_name+++def token() -> str:+ return secrets.token_hex(6)+++def external_aws_role_name(token: str) -> str:+ return f"test-aws-external-role-{token}"+++def destination_aws_role_name(token: str) -> str:+ return f"test-aws-destination-role-{token}"+++@pytest_asyncio.fixture+async def external_aws_role_arn(+ session: aioboto3.Session,+ account_id: str,+ identity_role: str,+ external_aws_role_name: str,+ destination_aws_role_name: str,+) -> collections.abc.AsyncIterator[str]:+ """Role used to assume a destination AWS role.++ This simulates the role shown to users of PostHog, so that they can grant+ this role permission to assume one of their roles.++ The current assumed role is granted permission to assume this role.+ """+ current_role_trust_policy = {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Principal": {+ "AWS": f"arn:aws:iam::{account_id}:role/aws-reserved/sso.amazonaws.com/{identity_role}",+ },+ "Action": "sts:AssumeRole",+ }+ ],+ }++ # For testing purposes, all roles may be under the same account, so a trust+ # policy is sufficient and this is unnecessary. But to closely mimic production+ # setup, we also add this policy.+ external_role_policy = {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Sid": "AllowAssumeDestinationRole",+ "Effect": "Allow",+ "Action": "sts:AssumeRole",+ "Resource": f"arn:aws:iam::{account_id}:role/{destination_aws_role_name}",+ }+ ],+ }++ async with aws_role(+ session,+ external_aws_role_name,+ description="External role used to assume a user's role",+ trust_policy=current_role_trust_policy,+ role_policy=external_role_policy,+ policy_name="AssumeDestinationRole",+ ) as arn:+ yield arn+++def external_id(request, aorganization) -> str | None:+ try:+ return request.param+ except Exception:+ return str(aorganization.id)+++@pytest_asyncio.fixture+async def destination_aws_role_arn(+ session: aioboto3.Session,+ external_aws_role_arn: str,+ bucket_name: str,+ aorganization,+ account_id: str,+ identity_role: str,+ destination_aws_role_name: str,+ external_id: str | None,+ kms_key_arn: str,+) -> collections.abc.AsyncIterator[str]:+ """Role with S3 permissions in a destination.++ This simulates a role in a user's destination. It can be assumed by our+ external role and ultimately grants access to S3.+ """+ external_trust_policy = {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Principal": {+ "AWS": external_aws_role_arn,+ },+ "Action": "sts:AssumeRole",+ }+ ],+ }+ if external_id is not None:+ external_trust_policy["Statement"][0]["Condition"] = { # type: ignore+ "StringEquals": {+ "sts:ExternalId": external_id,+ },+ }++ s3_policy = {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Sid": "BucketAccess",+ "Effect": "Allow",+ "Action": ["s3:ListBucket", "s3:GetBucketLocation"],+ "Resource": f"arn:aws:s3:::{bucket_name}",+ },+ {+ "Sid": "ObjectAccess",+ "Effect": "Allow",+ "Action": ["s3:PutObject", "s3:GetObject", "s3:DeleteObject", "s3:AbortMultipartUpload"],+ "Resource": f"arn:aws:s3:::{bucket_name}/*",+ },+ {+ "Sid": "KMSKeyAccess",+ "Effect": "Allow",+ "Action": ["kms:GenerateDataKey", "kms:Decrypt"],+ "Resource": kms_key_arn,+ },+ ],+ }++ async with aws_role(+ session,+ destination_aws_role_name,+ trust_policy=external_trust_policy,+ description="A user's role with access to S3",+ role_policy=s3_policy,+ policy_name="S3BucketAccess",+ ) as arn:+ yield arn+++async def aws_role(+ session: aioboto3.Session,+ role_name: str,+ /,+ *,+ description: str,+ trust_policy: dict,+ role_policy: dict | None = None,+ policy_name: str | None = None,+ max_attempts: int = 5,+ delay: int | float = 3.0,+) -> collections.abc.AsyncIterator[ARN]:+ async with session.client("iam") as iam:+ attempt = 0++ for attempt in range(max_attempts):+ try:+ resp = await iam.create_role(+ RoleName=role_name,+ MaxSessionDuration=3600,+ AssumeRolePolicyDocument=json.dumps(trust_policy),+ Description=description,+ )++ except botocore.exceptions.ClientError as exc:+ if (+ exc.response["Error"]["Code"] != "MalformedPolicyDocument"+ or "Invalid principal" not in exc.response["Error"]["Message"]+ ) and exc.response["Error"]["Code"] != "EntityAlreadyExists":+ raise pytest.skip(f"Failed with an unknown error when creating role: {type(exc)} {exc}")++ if attempt >= max_attempts:+ raise pytest.skip("Failed multiple times to create role")++ await asyncio.sleep(delay)++ except (+ botocore.exceptions.NoCredentialsError,+ botocore.exceptions.PartialCredentialsError,+ ):+ raise pytest.skip("Credentials error when attempting to create role")++ else:+ break++ if role_policy is not None and policy_name is not None:+ await iam.put_role_policy(+ RoleName=role_name,+ PolicyName=policy_name,+ PolicyDocument=json.dumps(role_policy),+ )++ yield resp["Role"]["Arn"]++ try:+ resp = await iam.list_role_policies(RoleName=role_name)+ for policy_name in resp.get("PolicyNames", []):+ await iam.delete_role_policy(RoleName=role_name, PolicyName=policy_name)+ await iam.delete_role(RoleName=role_name)++ except Exception:+ LOGGER.warning("Test role clean-up failed", name=role_name, arn=resp["Role"]["Arn"], exc_info=True)diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/test_activity_with_role_assumption.py b/products/batch_exports/backend/tests/temporal/destinations/s3/test_activity_with_role_assumption.pynew file mode 100644index 000000000000..dac7f4aa8cf5--- /dev/null+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/test_activity_with_role_assumption.py@@ -0,0 +1,207 @@+import uuid+import collections.abc++import pytest++from django.test import override_settings++import aioboto3+import pytest_asyncio+from temporalio.testing._activity import ActivityEnvironment++from posthog.models import Organization, Team+from posthog.models.integration import Integration++from products.batch_exports.backend.service import BatchExportModel+from products.batch_exports.backend.temporal.destinations.s3_batch_export import (+ PolicyStatement,+ S3InsertInputs,+ get_credentials_using_user_aws_role,+ s3_default_fields,+)+from products.batch_exports.backend.tests.temporal.destinations.s3.utils import (+ assert_clickhouse_records_in_s3,+ run_activity,+)++[email protected](scope="module")+def bucket_name(request) -> str:+ """Name for a test S3 bucket."""+ try:+ return request.param+ except AttributeError:+ return f"test-role-assumption-{str(uuid.uuid4())}"+++async def test_get_credentials_using_user_aws_role(+ external_aws_role_arn: str, destination_aws_role_arn: str, aorganization: Organization, bucket_name: str+):+ external_id = str(aorganization.id)++ with override_settings(BATCH_EXPORT_S3_EXTERNAL_ROLE_ARN=external_aws_role_arn):+ credentials = await get_credentials_using_user_aws_role(+ destination_aws_role_arn,+ external_id,+ session_name="test",+ policy_statements=[+ PolicyStatement(Effect="Allow", Action=["s3:ListBucket"], Resource="arn:aws:s3:::{bucket_name}")+ ],+ )++ session = aioboto3.Session(+ aws_access_key_id=credentials.aws_access_key_id,+ aws_secret_access_key=credentials.aws_secret_access_key,+ aws_session_token=credentials.aws_session_token,+ )++ async with session.client("sts") as sts:+ identity = await sts.get_caller_identity()++ # The ARNs between assumed and requested will not match exactly the same+ # So, we take out the role part that we care about and check that.+ assert identity["Arn"].rsplit("/", 2)[1] == destination_aws_role_arn.rsplit("/", 1)[1]+++@pytest_asyncio.fixture+async def integration(ateam: Team, destination_aws_role_arn: str) -> collections.abc.AsyncIterator[Integration]:+ integration = await Integration.objects.acreate(+ team_id=ateam.pk,+ kind=Integration.IntegrationKind.AWS_S3,+ integration_id="s3-role-assumption",+ config={"name": "test-role-assumption", "aws_role_arn": destination_aws_role_arn},+ )++ yield integration++ await integration.adelete()+++def kms_key_value(request) -> str | None:+ if not request.param:+ return None+ return request.getfixturevalue(request.param)+++ "kms_key_value",+ [None, "kms_key_id", "kms_key_arn"],+ indirect=True,+)[email protected]("model", [BatchExportModel(name="events", schema=None)])+async def test_insert_into_s3_activity_puts_data_into_s3_with_role_assumption(+ clickhouse_client,+ activity_environment: ActivityEnvironment,+ data_interval_start,+ data_interval_end,+ model: BatchExportModel,+ generate_test_data,+ integration: Integration,+ s3_client,+ external_aws_role_arn: str,+ ateam: Team,+ s3_bucket: str,+ region: str,+ kms_key_value: str | None,+):+ """Test the main S3 batch export activity using role assumption auth."""+ prefix = "batch-exports/" + str(uuid.uuid4())++ batch_export_id = str(uuid.uuid4())++ insert_inputs = S3InsertInputs(+ bucket_name=s3_bucket,+ region=region,+ prefix=prefix,+ team_id=ateam.pk,+ data_interval_start=data_interval_start.isoformat(),+ data_interval_end=data_interval_end.isoformat(),+ integration_id=integration.id,+ compression="zstd",+ file_format="Parquet",+ batch_export_model=model,+ batch_export_id=batch_export_id,+ destination_default_fields=s3_default_fields(),+ kms_key_id=kms_key_value,+ encryption="aws:kms" if kms_key_value is not None else None,+ )++ with override_settings(BATCH_EXPORT_S3_EXTERNAL_ROLE_ARN=external_aws_role_arn):+ result = await run_activity(activity_environment, insert_inputs)++ records_exported = result.records_completed+ bytes_exported = result.bytes_exported+ assert result.error is None++ events_to_export_created, _ = generate_test_data+ assert records_exported == len(events_to_export_created)++ assert isinstance(bytes_exported, int)+ assert bytes_exported > 0++ await assert_clickhouse_records_in_s3(+ s3_compatible_client=s3_client,+ clickhouse_client=clickhouse_client,+ bucket_name=s3_bucket,+ key_prefix=prefix,+ team_id=ateam.pk,+ data_interval_start=data_interval_start,+ data_interval_end=data_interval_end,+ batch_export_model=model,+ compression="zstd",+ file_format="Parquet",+ sort_key="uuid",+ )++[email protected]("external_id", ["not-an-org-id", None], indirect=True)[email protected]("model", [BatchExportModel(name="events", schema=None)])+async def test_insert_into_s3_activity_fails_role_assumption_with_missing_external_id(+ clickhouse_client,+ activity_environment: ActivityEnvironment,+ data_interval_start,+ data_interval_end,+ model: BatchExportModel,+ generate_test_data,+ integration: Integration,+ s3_client,+ external_aws_role_arn: str,+ bucket_name: str,+ ateam: Team,+ region: str,+ external_id: str | None,+):+ """Test the main S3 batch export activity fails role assumption with wrong external id.++ When the external id doesn't match, then we expect an access denied error, when the+ external id is not present at all, then we should raise our own error explaining that+ external id is required.+ """+ prefix = "batch-exports/" + str(uuid.uuid4())++ batch_export_id = str(uuid.uuid4())++ insert_inputs = S3InsertInputs(+ bucket_name=bucket_name,+ region=region,+ prefix=prefix,+ team_id=ateam.pk,+ data_interval_start=data_interval_start.isoformat(),+ data_interval_end=data_interval_end.isoformat(),+ integration_id=integration.id,+ compression="zstd",+ file_format="Parquet",+ batch_export_model=model,+ batch_export_id=batch_export_id,+ destination_default_fields=s3_default_fields(),+ )++ with override_settings(BATCH_EXPORT_S3_EXTERNAL_ROLE_ARN=external_aws_role_arn):+ result = await run_activity(activity_environment, insert_inputs)++ assert result.error is not None+ if external_id:+ assert "AccessDenied" in result.error.message+ else:+ assert "allows access without a required external id condition" in result.error.message