: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
refactor(batch-exports): drop credential fields from S3 export inputs (#90959)
Ross3347235bcbe4
diff --git a/products/batch_exports/backend/api/batch_export.py b/products/batch_exports/backend/api/batch_export.pyindex bbfe18b8fa40..777c4fbe3d49 100644--- a/products/batch_exports/backend/api/batch_export.py+++ b/products/batch_exports/backend/api/batch_export.py@@ -1474,18 +1474,8 @@ class BatchExportSerializer(serializers.ModelSerializer):if integration is None:raise serializers.ValidationError(f"Integration is required for {destination_type} batch exports")- # Credentials and the provider endpoint live in the integration. Only the submitted- # config is checked: rows migrated off inline credentials still hold these keys in- # stored config, and patching one must not resurface them as an error. Any other- # credential field is already rejected as unknown, since the input dataclasses never- # declared it.- integration_owned_fields = {"aws_access_key_id", "aws_secret_access_key", "endpoint_url"}- submitted_owned_fields = sorted(integration_owned_fields & config.keys())- if submitted_owned_fields:- raise serializers.ValidationError(- f"{destination_type} batch exports authenticate through their integration. "- f"Remove these fields from the configuration: {submitted_owned_fields}"- )+ # Credentials and the provider endpoint are not declared on the input dataclasses, so+ # `BatchExportDestinationSerializer.validate` already rejects them as unknown fields.# we already validate the required inputs in BatchExportDestinationSerializer::validate# so here we just ensure that the inputs are not emptydiff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.pyindex dcbd95fb1700..0d65e4874c16 100644--- a/products/batch_exports/backend/service.py+++ b/products/batch_exports/backend/service.py@@ -269,20 +269,18 @@ class S3BatchExportInputs(BaseBatchExportInputs):and on the worker side deserializes into `S3BatchExportInputs`, with anymissing fields falling through to the defaults declared here.+ Credentials and the provider endpoint are never carried here: the activity resolves them from+ the linked Integration at run time (see `integration_id`).+Attributes:bucket_name: The S3 bucket we are exporting to.region: The AWS region where the bucket is located.prefix: A prefix for the file name to be created in S3.- aws_access_key_id: Access key id used to authenticate with S3. Optional; integration-backed- exports resolve credentials from the linked Integration at run time (see `integration_id`),- while legacy exports carry them inline.- aws_secret_access_key: Secret access key used to authenticate with S3. See `aws_access_key_id`.compression: Compression algorithm to apply to exported files (e.g. "gzip", "brotli"), or None.file_format: File format of exported objects (e.g. "JSONLines", "Parquet"). Defaults to JSONLines.max_file_size_mb: The maximum file size in MB for each file to be uploaded.encryption: Server-side encryption algorithm to apply (e.g. "AES256", "aws:kms"), or None. AWS-only.kms_key_id: KMS key id to use when `encryption == "aws:kms"`, or None. AWS-only.- endpoint_url: Override endpoint for S3-compatible providers (e.g. MinIO, R2). None for AWS.use_virtual_style_addressing: Whether to use virtual-hosted-styleaddressing rather than path-style. None for AWS."""@@ -290,14 +288,11 @@ class S3BatchExportInputs(BaseBatchExportInputs):bucket_name: strregion: strprefix: str- aws_access_key_id: str | None = None- aws_secret_access_key: str | None = field(default=None, repr=False)compression: str | None = Nonefile_format: str = "JSONLines"max_file_size_mb: int | None = Noneencryption: str | None = Nonekms_key_id: str | None = None- endpoint_url: str | None = Noneuse_virtual_style_addressing: bool = False@@ -305,16 +300,14 @@ class S3BatchExportInputs(BaseBatchExportInputs):class S3FamilyBaseInputs(BaseBatchExportInputs):"""Shared fields for every S3-family destination.- Per-destination dataclasses extend this with provider-specific fields. Credentials are optional:- integration-backed exports resolve them from the linked Integration at run time (see- `integration_id`), while legacy exports carry them inline.+ Per-destination dataclasses extend this with provider-specific fields. Credentials are never+ carried here: the activity resolves them from the linked Integration at run time (see+ `integration_id`)."""bucket_name: strregion: strprefix: str- aws_access_key_id: str | None = None- aws_secret_access_key: str | None = field(default=None, repr=False)compression: str | None = Nonefile_format: str = "JSONLines"max_file_size_mb: int | None = None@@ -328,16 +321,15 @@ class AwsS3BatchExportInputs(S3FamilyBaseInputs):kms_key_id: str | None = None-@dataclass(kw_only=True)+@dataclass(frozen=False, kw_only=True)class S3CompatibleBatchExportInputs(S3FamilyBaseInputs):"""Inputs for a non-AWS S3-compatible batch export.Covers providers like DigitalOcean Spaces, Cloudflare R2, Hetzner, OVH, Backblaze, etc.- `endpoint_url` is resolved from the linked Integration at run time when `integration_id` is set,- otherwise carried inline (legacy).+ `endpoint_url` lives on the linked Integration alongside the credentials, so it is resolved at+ run time rather than configured per export."""- endpoint_url: str | None = Noneuse_virtual_style_addressing: bool = Falsediff --git a/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py b/products/batch_exports/backend/temporal/destinations/file_download_batch_export.pyindex 341b8f8947e4..04c590629e83 100644--- a/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py@@ -31,9 +31,11 @@ from products.batch_exports.backend.temporal.batch_exports import (start_batch_export_run,)from products.batch_exports.backend.temporal.destinations.s3_batch_export import (+ S3_WRITE_NON_RETRYABLE_ERROR_TYPES,+ ResolvedS3Credentials,S3BatchExportResult,S3InsertInputs,- insert_into_s3_activity_from_stage,+ insert_into_s3_from_stage,s3_default_fields,)from products.batch_exports.backend.temporal.pipeline.entrypoint import execute_batch_export_using_internal_stage@@ -46,7 +48,9 @@ FILE_DOWNLOAD_PREFIX = ("batch-exports/{batch_export_id}/{batch_export_run_id}/{{data_interval_start}}-{{data_interval_end}}")-NON_RETRYABLE_ERROR_TYPES = ()+# This export runs the same S3 write as a batch export, so it fails the same way. It has no+# Integration, so the integration errors an S3 batch export can raise are not reachable here.+NON_RETRYABLE_ERROR_TYPES = S3_WRITE_NON_RETRYABLE_ERROR_TYPESSESSION = aioboto3.Session()@@ -269,11 +273,15 @@ async def export_to_file_download_bucket_with_temporary_credentials(inputs: Expobatch_export_model=inputs.batch_export.batch_export_model,batch_export_id=inputs.batch_export.batch_export_id,destination_default_fields=inputs.batch_export.destination_default_fields,- refresh_credentials=refresh_credentials,)- result = await insert_into_s3_activity_from_stage(s3_insert_inputs)-- return result+ # Minting the first credentials calls AWS STS, and this activity heartbeats every 10 seconds,+ # so the call runs under the heartbeater rather than ahead of it.+ async with Heartbeater():+ resolved_credentials = ResolvedS3Credentials(+ credentials=await refresh_credentials(),+ refresh_using=refresh_credentials,+ )+ return await insert_into_s3_from_stage(s3_insert_inputs, resolved_credentials)@dataclasses.dataclassdiff --git a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py b/products/batch_exports/backend/temporal/destinations/s3_batch_export.pyindex d3258ced3fbd..88ac5ff6dc2e 100644--- a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/s3_batch_export.py@@ -26,6 +26,7 @@ from structlog.contextvars import bind_contextvarsfrom temporalio import activity, exceptions, workflowfrom temporalio.common import RetryPolicy+from posthog.dataclasses import frozenfrom posthog.models.integration import (AWSS3Integration,AWSS3RoleBasedIntegration,@@ -72,7 +73,9 @@ from products.batch_exports.backend.temporal.pipeline.types import BatchExportRefrom products.batch_exports.backend.temporal.queue import RecordBatchQueue, wait_for_schema_or_producerfrom products.batch_exports.backend.temporal.utils import handle_non_retryable_errors-NON_RETRYABLE_ERROR_TYPES = (+# Errors that any write to S3 can raise, whichever bucket it targets. The file download+# export shares these, since it runs the same write against a PostHog-owned bucket.+S3_WRITE_NON_RETRYABLE_ERROR_TYPES = (# S3 parameter validation failed."ParamValidationError",# This error usually indicates credentials are incorrect or permissions are missing.@@ -93,6 +96,11 @@ NON_RETRYABLE_ERROR_TYPES = ("UnsupportedCompressionError",# Invalid S3 credentials"InvalidCredentialsError",+)++# Only a customer's S3 export authenticates through an Integration, so only it can fail this way.+NON_RETRYABLE_ERROR_TYPES = (+ *S3_WRITE_NON_RETRYABLE_ERROR_TYPES,# The export has no linked Integration to authenticate with"MissingIntegrationError",# The linked Integration was deleted or doesn't belong to the team@@ -122,6 +130,20 @@ SESSION = aioboto3.Session()RefreshCoroutine = typing.Callable[[], typing.Awaitable[AWSCredentials]]+@frozen+class ResolvedS3Credentials:+ """Everything a write needs to reach and authenticate against its target S3 endpoint.++ Resolved before the write starts, as each caller obtains credentials differently. Only an+ S3-compatible provider needs an `endpoint_url`; AWS and PostHog's own bucket use the default.+ `refresh_using` mints new credentials when temporary ones expire during a long upload.+ """++ credentials: AWSCredentials+ endpoint_url: str | None = None+ refresh_using: RefreshCoroutine | None = None++class UnsupportedFileFormatError(Exception):"""Raised when an unsupported file format is requested."""@@ -184,31 +206,26 @@ async def _get_s3_integration(@dataclasses.dataclass(frozen=False, kw_only=True)class S3InsertInputs(BatchExportInsertInputs):- """Inputs for S3 exports."""+ """Inputs for S3 exports.- # TODO: do _not_ store credentials in temporal inputs. It makes it very hard- # to keep track of where credentials are being stored and increases the- # attach surface for credential leaks.+ No credentials are carried here. An export resolves them from the Integration named by+ `integration_id`.+ """bucket_name: strregion: strprefix: str- # When set, credentials (and endpoint_url for S3-compatible) are resolved from this Integration- # at run time; otherwise the inline credentials below are used (legacy path).+ # Optional only so payloads written before it still deserialize. The activity fails without+ # retrying when it has no integration to authenticate with.+ # TODO: maybe we can make this required in future?integration_id: int | None = None- aws_access_key_id: str | None = None- aws_secret_access_key: str | None = dataclasses.field(default=None, repr=False)- aws_session_token: str | None = dataclasses.field(default=None, repr=False)compression: str | None = Noneencryption: str | None = Nonekms_key_id: str | None = None- endpoint_url: str | None = None# TODO: In Python 3.11, this could be a enum.StrEnum.file_format: str = "JSONLines"max_file_size_mb: int | None = Noneuse_virtual_style_addressing: bool = False- # Only usable when calling the activity as a function, Temporal cannot serialize this.- refresh_credentials: RefreshCoroutine | None = Nonedef get_s3_key_from_inputs(inputs: S3InsertInputs, file_number: int = 0) -> str:@@ -348,9 +365,6 @@ class S3BatchExportWorkflow(PostHogWorkflow):prefix=inputs.prefix,team_id=inputs.team_id,integration_id=inputs.integration_id,- aws_access_key_id=inputs.aws_access_key_id,- aws_secret_access_key=inputs.aws_secret_access_key,- endpoint_url=inputs.endpoint_url or None,data_interval_start=data_interval.start.isoformat() if not should_backfill_from_beginning else None,data_interval_end=data_interval.end.isoformat(),compression=inputs.compression,@@ -591,6 +605,86 @@ async def s3_client(raise+async def _resolve_credentials_from_integration(inputs: S3InsertInputs) -> ResolvedS3Credentials:+ """Resolve an export's S3 credentials from the Integration it links to."""+ if inputs.integration_id is None:+ raise MissingIntegrationError(inputs.batch_export_id)++ integration = await _get_s3_integration(inputs.integration_id, inputs.team_id)++ if isinstance(integration, AWSS3Integration):+ return ResolvedS3Credentials(+ credentials=AWSCredentials(+ aws_access_key_id=integration.aws_access_key_id,+ aws_secret_access_key=integration.aws_secret_access_key,+ )+ )++ if isinstance(integration, S3CompatibleIntegration):+ return ResolvedS3Credentials(+ credentials=AWSCredentials(+ aws_access_key_id=integration.aws_access_key_id,+ aws_secret_access_key=integration.aws_secret_access_key,+ ),+ endpoint_url=integration.endpoint_url,+ )++ team = await Team.objects.aget(id=inputs.team_id)+ external_id = f"posthog-{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,+ )+ )++ refresh_using = functools.partial(+ get_credentials_using_user_aws_role,+ integration.aws_role_arn,+ external_id,+ session_name=f"PostHog-batch-exports-{inputs.batch_export_id}",+ policy_statements=policy_statements,+ )+ return ResolvedS3Credentials(credentials=await refresh_using(), refresh_using=refresh_using)++@activity.defn@handle_non_retryable_errors(NON_RETRYABLE_ERROR_TYPES)async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> S3BatchExportResult:@@ -607,6 +701,22 @@ async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> S3BatchEOur S3 batch exports also support customising the max S3 file size, different file formats,compression, etc, which ClickHouse's S3 functions may not support."""+ # Resolving credentials reads the database, and assuming a role calls AWS STS. Both run+ # under the heartbeater, so a slow one cannot exhaust the activity's heartbeat timeout.+ async with Heartbeater():+ resolved_credentials = await _resolve_credentials_from_integration(inputs)+ return await insert_into_s3_from_stage(inputs, resolved_credentials)+++async def insert_into_s3_from_stage(+ inputs: S3InsertInputs, resolved_credentials: ResolvedS3Credentials+) -> S3BatchExportResult:+ """Write data staged in our internal S3 stage to a target S3 bucket.++ The caller resolves credentials first, because an export takes them from its Integration+ while the file download export mints temporary ones for a PostHog-owned bucket. The caller+ is an activity, so it owns the heartbeater this runs under.+ """bind_contextvars(team_id=inputs.team_id,destination="S3",@@ -619,175 +729,95 @@ async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> S3BatchEif inputs.compression is not None and inputs.compression not in SUPPORTED_COMPRESSIONS[inputs.file_format]:raise UnsupportedCompressionError(inputs.compression)- async with Heartbeater():- # Customer exports resolve credentials from their linked integration. The internal- # file-download export instead passes a `refresh_credentials` coroutine that mints- # scoped credentials for PostHog's own bucket. One of the two must be present.- endpoint_url = inputs.endpoint_url- refresh_credentials = inputs.refresh_credentials-- if inputs.integration_id is not None:- integration = await _get_s3_integration(inputs.integration_id, inputs.team_id)-- if isinstance(integration, AWSS3Integration):- credentials = AWSCredentials(- 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)- external_id = f"posthog-{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 = resolved_credentials.credentials+ endpoint_url = resolved_credentials.endpoint_url+ refresh_credentials = resolved_credentials.refresh_using- refresh_credentials = functools.partial(- get_credentials_using_user_aws_role,- integration.aws_role_arn,- external_id,- session_name=f"PostHog-batch-exports-{inputs.batch_export_id}",- policy_statements=policy_statements,- )- credentials = await refresh_credentials()-- if isinstance(integration, S3CompatibleIntegration):- credentials = AWSCredentials(- aws_access_key_id=integration.aws_access_key_id,- aws_secret_access_key=integration.aws_secret_access_key,- )- endpoint_url = integration.endpoint_url+ 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),+ )- elif refresh_credentials is not None:- credentials = await refresh_credentials()- else:- raise MissingIntegrationError(inputs.batch_export_id)+ queue = RecordBatchQueue(max_size_bytes=settings.BATCH_EXPORT_S3_RECORD_BATCH_QUEUE_MAX_SIZE_BYTES)+ producer = ProducerFromInternalStage()+ assert inputs.batch_export_id is not None+ producer_task = await producer.start(+ queue=queue,+ batch_export_id=inputs.batch_export_id,+ data_interval_start=inputs.data_interval_start,+ data_interval_end=inputs.data_interval_end,+ max_record_batch_size_bytes=1024 * 1024 * 60, # 60MB+ stage_folder=inputs.stage_folder,+ )- external_logger = EXTERNAL_LOGGER.bind()+ record_batch_schema = await wait_for_schema_or_producer(queue, producer_task)+ if record_batch_schema is None:external_logger.info(- "Batch exporting range %s - %s to S3: %s",+ "Batch export will finish early as there is no data matching specified filters in range %s - %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()- assert inputs.batch_export_id is not None- producer_task = await producer.start(- queue=queue,- batch_export_id=inputs.batch_export_id,- data_interval_start=inputs.data_interval_start,- data_interval_end=inputs.data_interval_end,- max_record_batch_size_bytes=1024 * 1024 * 60, # 60MB- stage_folder=inputs.stage_folder,)- record_batch_schema = await wait_for_schema_or_producer(queue, producer_task)- if record_batch_schema is None:- external_logger.info(- "Batch export will finish early as there is no data matching specified filters in range %s - %s",- inputs.data_interval_start or "START",- inputs.data_interval_end or "END",- )+ return S3BatchExportResult(records_completed=0, bytes_exported=0)- return S3BatchExportResult(records_completed=0, bytes_exported=0)+ record_batch_schema = pa.schema(+ # NOTE: For some reason, some batches set non-nullable fields as non-nullable, whereas other+ # record batches have them as nullable.+ # Until we figure it out, we set all fields to nullable. There are some fields we know+ # are not nullable, but I'm opting for the more flexible option until we out why schemas differ+ # between batches.+ [field.with_nullable(True) for field in record_batch_schema]+ )- record_batch_schema = pa.schema(- # NOTE: For some reason, some batches set non-nullable fields as non-nullable, whereas other- # record batches have them as nullable.- # Until we figure it out, we set all fields to nullable. There are some fields we know- # are not nullable, but I'm opting for the more flexible option until we out why schemas differ- # between batches.- [field.with_nullable(True) for field in record_batch_schema]+ json_columns = ("properties", "person_properties", "set", "set_once")+ if inputs.file_format.lower() == "jsonlines":+ transformer = get_json_stream_transformer(+ compression=inputs.compression,+ include_inserted_at=True,+ max_file_size_bytes=inputs.max_file_size_mb * 1024 * 1024 if inputs.max_file_size_mb else 0,+ )+ else:+ transformer = ParquetStreamTransformer(+ compression=inputs.compression,+ include_inserted_at=True,+ max_file_size_bytes=inputs.max_file_size_mb * 1024 * 1024 if inputs.max_file_size_mb else 0,)- json_columns = ("properties", "person_properties", "set", "set_once")- if inputs.file_format.lower() == "jsonlines":- transformer = get_json_stream_transformer(- compression=inputs.compression,- include_inserted_at=True,- max_file_size_bytes=inputs.max_file_size_mb * 1024 * 1024 if inputs.max_file_size_mb else 0,- )- else:- transformer = ParquetStreamTransformer(- compression=inputs.compression,- include_inserted_at=True,- max_file_size_bytes=inputs.max_file_size_mb * 1024 * 1024 if inputs.max_file_size_mb else 0,- )-- async with s3_client(- credentials,- use_virtual_style_addressing=inputs.use_virtual_style_addressing,- region=inputs.region,- endpoint_url=endpoint_url,- refresh_using=refresh_credentials,- ) 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,- checksum_algorithm="CRC64NVME" if endpoint_url is None else None,- )-- 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(+ credentials,+ use_virtual_style_addressing=inputs.use_virtual_style_addressing,+ region=inputs.region,+ endpoint_url=endpoint_url,+ refresh_using=refresh_credentials,+ ) 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,+ checksum_algorithm="CRC64NVME" if endpoint_url is None else None,+ )- return S3BatchExportResult(- bytes_exported=result.bytes_exported,- records_completed=result.records_completed,- records_failed=result.records_failed,- error=result.error,- files_uploaded=consumer.files_uploaded,+ 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,+ records_failed=result.records_failed,+ error=result.error,+ files_uploaded=consumer.files_uploaded,+ )+class ConcurrentS3Consumer(Consumer):"""A consumer that uploads chunks of data to S3 concurrently.diff --git a/products/batch_exports/backend/tests/api/test_create_s3.py b/products/batch_exports/backend/tests/api/test_create_s3.pyindex d025cd5ae44b..c48be3644c68 100644--- a/products/batch_exports/backend/tests/api/test_create_s3.py+++ b/products/batch_exports/backend/tests/api/test_create_s3.py@@ -131,58 +131,17 @@ def test_create_s3_family_batch_export_validates_empty_inputs(assert response.json()["detail"] == "The following inputs are empty: ['bucket_name', 'region']"- "destination_type,integration_fixture,owned_field",- [- ("AwsS3", "aws_s3_integration", "aws_access_key_id"),- ("AwsS3", "aws_s3_integration", "aws_secret_access_key"),- ("S3Compatible", "s3_compatible_integration", "aws_access_key_id"),- ("S3Compatible", "s3_compatible_integration", "aws_secret_access_key"),- # `endpoint_url` is an S3Compatible-only field; AwsS3 rejects it as unknown instead.- ("S3Compatible", "s3_compatible_integration", "endpoint_url"),- ],-)-def test_create_s3_family_batch_export_rejects_integration_owned_fields(- client: HttpClient,- temporal,- organization,- team,- user,- destination_type,- integration_fixture,- owned_field,- request,-):- """Credentials and the provider endpoint belong to the integration, so config may not carry them.-- An accepted value here would be persisted in `config` and copied into the export's Temporal- schedule arguments.- """- integration = request.getfixturevalue(integration_fixture)- client.force_login(user)- response = create_batch_export(- client,- team.pk,- {- "name": "my-export",- "interval": "hour",- "destination": {- "type": destination_type,- "config": {**_S3_FAMILY_BASE_CONFIG, owned_field: "belongs-in-the-integration"},- "integration": integration.id,- },- },- )- assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()- assert response.json()["detail"] == (- f"{destination_type} batch exports authenticate through their integration. "- f"Remove these fields from the configuration: ['{owned_field}']"- )--@pytest.mark.parametrize("destination_type,extra_config,offending_field",[+ # Credentials and the provider endpoint live in the integration, so they are not+ # configuration. An accepted value would be persisted in `config` and copied into the+ # export's Temporal schedule arguments.+ ("AwsS3", {"aws_access_key_id": "belongs-in-the-integration"}, "aws_access_key_id"),+ ("AwsS3", {"aws_secret_access_key": "belongs-in-the-integration"}, "aws_secret_access_key"),+ ("S3Compatible", {"aws_access_key_id": "belongs-in-the-integration"}, "aws_access_key_id"),+ ("S3Compatible", {"aws_secret_access_key": "belongs-in-the-integration"}, "aws_secret_access_key"),+ ("S3Compatible", {"endpoint_url": "https://localhost:9000"}, "endpoint_url"),# AwsS3 rejects S3-compatible-only fields.("AwsS3", {"endpoint_url": "https://localhost:9000"}, "endpoint_url"),("AwsS3", {"use_virtual_style_addressing": True}, "use_virtual_style_addressing"),diff --git a/products/batch_exports/backend/tests/api/test_test.py b/products/batch_exports/backend/tests/api/test_test.pyindex 2cda371310df..61c6301f0f5c 100644--- a/products/batch_exports/backend/tests/api/test_test.py+++ b/products/batch_exports/backend/tests/api/test_test.py@@ -203,9 +203,8 @@ def test_run_test_step_rejects_destination_type_change():"""A test step must not be able to change the destination type of an existing export.- Otherwise a caller could, for example, switch an "AwsS3" export (no `endpoint_url`) to the- legacy "S3" type, supply an `endpoint_url` they control, and have the integration's credentials- tested against that endpoint.+ Otherwise a caller could point an export's integration at a destination it was never linked to,+ and have its credentials tested against that destination."""client.force_login(user)@@ -215,7 +214,8 @@ def test_run_test_step_rejects_destination_type_change("name": "my-production-s3-bucket-destination","destination": {"type": "S3",- "config": {"endpoint_url": "https://attacker.example"},+ # Valid configuration for the submitted type, so the type change is what gets rejected.+ "config": {"bucket_name": "my-bucket", "region": "us-east-1", "prefix": "events/"},},"interval": "hour",}diff --git a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_activity.py b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_activity.pyindex 2d544e1b7c95..9b0d513aec84 100644--- a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_activity.py+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_activity.py@@ -65,7 +65,7 @@ async def test_export_to_file_download_bucket_puts_data_into_s3("""Test that export_to_file_download_bucket_with_temporary_credentials exports data to S3.The activity obtains temporary credentials via STS role assumption, constructs- S3InsertInputs, and delegates to insert_into_s3_activity_from_stage. We verify+ S3InsertInputs, and delegates to insert_into_s3_from_stage. We verifythe data ends up in the expected S3 location and matches what ClickHouse produces."""if compression and compression not in SUPPORTED_COMPRESSIONS[file_format]:diff --git a/products/batch_exports/backend/tests/test_service.py b/products/batch_exports/backend/tests/test_service.pyindex ed8c76f96a05..8e305d685dbf 100644--- a/products/batch_exports/backend/tests/test_service.py+++ b/products/batch_exports/backend/tests/test_service.py@@ -39,8 +39,6 @@ DESTINATION_INPUTS = {bucket_name="bucket",region="us-east-1",prefix="prefix/",- aws_access_key_id="key",- aws_secret_access_key="secret",use_virtual_style_addressing="true", # type: ignoremax_file_size_mb="100", # type: ignore),@@ -132,8 +130,6 @@ class TestTypeCoercionInBatchExportInputs:bucket_name="bucket",region="us-east-1",prefix="prefix/",- aws_access_key_id="key",- aws_secret_access_key="secret",max_file_size_mb=None,)assert inputs.max_file_size_mb is None