: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(s3): Update tests to cover both AWSS3 and S3Compatible (#73228)
Tomás Farías Santana6b568081c980
diff --git a/products/batch_exports/backend/api/destination_tests/__init__.py b/products/batch_exports/backend/api/destination_tests/__init__.pyindex c04496166337..969ab6a99a25 100644--- a/products/batch_exports/backend/api/destination_tests/__init__.py+++ b/products/batch_exports/backend/api/destination_tests/__init__.py@@ -1,5 +1,4 @@from products.batch_exports.backend.api.destination_tests.base import DestinationTest-from products.batch_exports.backend.models.batch_export import S3_FAMILY_TYPESdef get_destination_test(@@ -11,10 +10,14 @@ def get_destination_test((databricks, google-cloud-bigquery, snowflake, etc.). Importing them lazily keeps theSDKs off the API import path — only the requested destination's SDK loads."""- if destination in S3_FAMILY_TYPES:- from products.batch_exports.backend.api.destination_tests.s3 import S3DestinationTest # noqa: PLC0415+ if destination in ("S3", "S3Compatible"):+ from products.batch_exports.backend.api.destination_tests.s3 import S3CompatibleDestinationTest # noqa: PLC0415- return S3DestinationTest()+ return S3CompatibleDestinationTest()+ elif destination == "AwsS3":+ from products.batch_exports.backend.api.destination_tests.s3 import AwsS3DestinationTest # noqa: PLC0415++ return AwsS3DestinationTest()elif destination == "BigQuery":from products.batch_exports.backend.api.destination_tests.bigquery import ( # noqa: PLC0415BigQueryDestinationTest,diff --git a/products/batch_exports/backend/api/destination_tests/s3.py b/products/batch_exports/backend/api/destination_tests/s3.pyindex 970275b5f13c..0d5e5e2d165c 100644--- a/products/batch_exports/backend/api/destination_tests/s3.py+++ b/products/batch_exports/backend/api/destination_tests/s3.py@@ -6,6 +6,93 @@ from products.batch_exports.backend.api.destination_tests.base import (DestinationTestStepResult,Status,)+from products.batch_exports.backend.temporal.destinations.s3_batch_export import (+ InvalidCredentialsError,+ PolicyStatement,+ get_credentials_using_user_aws_role,+)+++class S3AssumeRoleTestStep(DestinationTestStep):+ """Test whether we can assume a configured AWS role.+++ Attributes:+ aws_role_arn: AWS role ARN we are testing.+ """++ name = "Ensure we can assume provided AWS role"+ description = (+ "Ensure the configured AWS role ARN exists and that we have the required trust relationship to assume it."+ )++ def __init__(+ self,+ aws_role_arn: str | None = None,+ bucket_name: str | None = None,+ organization_id: str | None = None,+ max_attempts: int = 1,+ ) -> None:+ super().__init__()+ self.aws_role_arn = aws_role_arn+ self.bucket_name = bucket_name+ self.organization_id = organization_id+ # This test verifies user-provided config, where failures are expected, so+ # default to a single attempt and report promptly rather than retrying.+ self.max_attempts = max_attempts++ def _is_configured(self) -> bool:+ # Always considered configured: when there is no role ARN to assume (e.g.+ # key-based auth) the step reports SKIPPED rather than failing.+ return True++ async def _run_step(self) -> DestinationTestStepResult:+ """Run this test step."""+ from botocore.exceptions import ClientError++ if self.aws_role_arn is None or self.bucket_name is None:+ return DestinationTestStepResult(status=Status.SKIPPED, message="No configured AWS role ARN, skipping test")++ external_id = f"posthog-{self.organization_id}"+ try:+ _ = await get_credentials_using_user_aws_role(+ self.aws_role_arn,+ external_id,+ session_name="PostHog-batch-exports-test",+ policy_statements=[+ PolicyStatement(+ Effect="Allow", Action=["s3:ListBucket"], Resource=f"arn:aws:s3:::{self.bucket_name}"+ )+ ],+ max_attempts=self.max_attempts,+ )+ except InvalidCredentialsError as err:+ return DestinationTestStepResult(+ status=Status.FAILED,+ # The error message here is already pretty clear.+ message=str(err),+ )++ except ClientError as err:+ error_code = err.response.get("Error", {}).get("Code")+ if error_code == "AccessDenied":+ # We can't really separate what went wrong here.+ return DestinationTestStepResult(+ status=Status.FAILED,+ message=f"We couldn't assume '{self.aws_role_arn}' due to an 'AccessDenied' error. Ensure that the trust policy attached to the role allows 'sts:AssumeRole' for the PostHog role, that the 'ExternalId' condition is set, and that the role actually exists.",+ )++ return DestinationTestStepResult(+ status=Status.FAILED,+ message=f"An unknown error occurred when trying to assume '{self.aws_role_arn}': {err}",+ )+ except Exception as err:+ return DestinationTestStepResult(+ status=Status.FAILED,+ message=f"An unknown error occurred when trying to assume '{self.aws_role_arn}': {err}",+ )++ return DestinationTestStepResult(status=Status.PASSED)class S3EnsureBucketTestStep(DestinationTestStep):@@ -32,6 +119,9 @@ class S3EnsureBucketTestStep(DestinationTestStep):endpoint_url: str | None = None,aws_access_key_id: str | None = None,aws_secret_access_key: str | None = None,+ aws_role_arn: str | None = None,+ organization_id: str | None = None,+ max_attempts: int = 1,) -> None:super().__init__()self.bucket_name = bucket_name@@ -39,11 +129,22 @@ class S3EnsureBucketTestStep(DestinationTestStep):self.endpoint_url = endpoint_urlself.aws_access_key_id = aws_access_key_idself.aws_secret_access_key = aws_secret_access_key+ self.aws_role_arn = aws_role_arn+ self.organization_id = organization_id+ # This test verifies user-provided config, where failures are expected, so+ # default to a single attempt and report promptly rather than retrying.+ self.max_attempts = max_attemptsdef _is_configured(self) -> bool:"""Ensure required configuration parameters are set."""- if self.bucket_name is None or self.aws_access_key_id is None or self.aws_secret_access_key is None:+ if self.bucket_name is None:+ return False++ if (self.aws_role_arn is None or self.organization_id is None) and (+ self.aws_access_key_id is None or self.aws_secret_access_key is None+ ):return False+return Trueasync def _run_step(self) -> DestinationTestStepResult:@@ -52,11 +153,38 @@ class S3EnsureBucketTestStep(DestinationTestStep):from botocore.exceptions import ClientErrorsession = aioboto3.Session()++ aws_access_key_id = self.aws_access_key_id+ aws_secret_access_key = self.aws_secret_access_key+ aws_session_token = None++ if self.aws_role_arn is not None:+ external_id = f"posthog-{self.organization_id}"++ credentials = await get_credentials_using_user_aws_role(+ self.aws_role_arn,+ external_id,+ session_name="PostHog-batch-exports-test",+ policy_statements=[+ PolicyStatement(+ Effect="Allow", Action=["s3:ListBucket"], Resource=f"arn:aws:s3:::{self.bucket_name}"+ )+ ],+ max_attempts=self.max_attempts,+ )++ 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,+ )+async with session.client("s3",region_name=self.region,- aws_access_key_id=self.aws_access_key_id,- aws_secret_access_key=self.aws_secret_access_key,+ aws_access_key_id=aws_access_key_id,+ aws_secret_access_key=aws_secret_access_key,+ aws_session_token=aws_session_token,endpoint_url=self.endpoint_url,) as client:assert self.bucket_name is not None@@ -88,7 +216,7 @@ class S3EnsureBucketTestStep(DestinationTestStep):return DestinationTestStepResult(status=Status.PASSED)-class S3DestinationTest(DestinationTest):+class S3CompatibleDestinationTest(DestinationTest):"""A concrete implementation of a `DestinationTest` for S3.Attributes:@@ -126,3 +254,53 @@ class S3DestinationTest(DestinationTest):aws_secret_access_key=self.aws_secret_access_key,)]+++class AwsS3DestinationTest(DestinationTest):+ """A concrete implementation of a `DestinationTest` for AWS S3.++ Attributes:+ bucket_name: The bucket we are batch exporting to.+ region: Region where the bucket is supposed to be.+ aws_access_key_id: Access key ID for the bucket.+ aws_secret_access_key: Secret access key for the bucket.+ aws_role_arn: Role to assume to access the bucket, if not using+ long-lived credentials.+ """++ def __init__(self):+ self.bucket_name = None+ self.region = None+ self.aws_access_key_id = None+ self.aws_secret_access_key = None+ self.aws_role_arn = None+ self.organization_id: str | None = None++ def configure(self, **kwargs):+ """Configure this test with necessary attributes."""+ self.bucket_name = kwargs.get("bucket_name", None)+ self.region = kwargs.get("region", None)+ self.aws_access_key_id = kwargs.get("aws_access_key_id", None)+ self.aws_secret_access_key = kwargs.get("aws_secret_access_key", None)+ self.aws_role_arn = kwargs.get("aws_role_arn", None)++ integration = kwargs.get("integration", None)+ if integration is not None:+ self.organization_id = integration.team.organization_id++ @property+ def steps(self) -> collections.abc.Sequence[DestinationTestStep]:+ """Sequence of test steps that make up this destination test."""+ return [+ S3AssumeRoleTestStep(+ aws_role_arn=self.aws_role_arn, bucket_name=self.bucket_name, organization_id=self.organization_id+ ),+ S3EnsureBucketTestStep(+ bucket_name=self.bucket_name,+ region=self.region,+ aws_access_key_id=self.aws_access_key_id,+ aws_secret_access_key=self.aws_secret_access_key,+ aws_role_arn=self.aws_role_arn,+ organization_id=self.organization_id,+ ),+ ]diff --git a/products/batch_exports/backend/tests/api/destination_tests/conftest.py b/products/batch_exports/backend/tests/api/destination_tests/conftest.pynew file mode 100644index 000000000000..290522b0b93d--- /dev/null+++ b/products/batch_exports/backend/tests/api/destination_tests/conftest.py@@ -0,0 +1,234 @@+import os+import uuid+import secrets+import collections.abc++import pytest++import aioboto3+import pytest_asyncio+import botocore.exceptions++from products.batch_exports.backend.tests.temporal.utils.s3 import aws_role, delete_all_from_s3++TEST_ROOT_BUCKET = "test-destination-tests"+TEST_REGION = os.getenv("TEST_S3_BUCKET_REGION", "us-east-1")++[email protected](scope="module")+def region() -> str:+ return TEST_REGION+++def token() -> str:+ return secrets.token_hex(6)+++def external_aws_role_name(token: str) -> str:+ return f"test-destination-external-role-{token}"+++def destination_aws_role_name(token: str) -> str:+ return f"test-destination-role-{token}"+++@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 account_id(session: aioboto3.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: aioboto3.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+++# Named distinctly from the test module's function-scoped `bucket_name` fixture (used by+# the MinIO tests) so this module-scoped fixture is not shadowed, which would cause a+# ScopeMismatch when the module-scoped `aws_bucket` requests it.[email protected](scope="module")+def aws_bucket_name() -> str:+ """Name for a test S3 bucket."""+ return f"{TEST_ROOT_BUCKET}-{str(uuid.uuid4())}"+++@pytest_asyncio.fixture(scope="module")+async def aws_bucket(+ session: aioboto3.Session, aws_bucket_name: str, region: str+) -> collections.abc.AsyncIterator[str]:+ """A real S3 bucket the destination role is granted access to."""+ async with session.client("s3") as s3_client:+ try:+ await s3_client.create_bucket(Bucket=aws_bucket_name, ACL="private")+ except (+ botocore.exceptions.NoCredentialsError,+ botocore.exceptions.PartialCredentialsError,+ botocore.exceptions.ClientError,+ ):+ raise pytest.skip("Could not setup S3 bucket")++ yield aws_bucket_name++ try:+ await delete_all_from_s3(s3_client, aws_bucket_name, key_prefix="")+ await s3_client.delete_bucket(Bucket=aws_bucket_name)+ except Exception:+ pass+++@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 PostHog users so that they can grant it+ permission to assume one of their roles.+ """+ 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",+ }+ ],+ }++ 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:+ """External id used in the destination role's trust policy.++ Parametrize indirectly to test wrong (or missing) external ids.+ """+ try:+ return request.param+ except AttributeError:+ return f"posthog-{aorganization.id}"+++@pytest_asyncio.fixture+async def destination_aws_role_arn(+ session: aioboto3.Session,+ external_aws_role_arn: str,+ destination_aws_role_name: str,+ aws_bucket: str,+ external_id: str | None,+) -> 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 grants access to S3. When `external_id` is `None`, the+ trust policy omits the external id condition (used to test that path).+ """+ statement: dict[str, object] = {+ "Effect": "Allow",+ "Principal": {+ "AWS": external_aws_role_arn,+ },+ "Action": "sts:AssumeRole",+ }+ if external_id is not None:+ statement["Condition"] = {+ "StringEquals": {+ "sts:ExternalId": external_id,+ },+ }++ external_trust_policy = {+ "Version": "2012-10-17",+ "Statement": [statement],+ }++ s3_policy = {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Sid": "BucketAccess",+ "Effect": "Allow",+ "Action": ["s3:ListBucket", "s3:GetBucketLocation"],+ "Resource": f"arn:aws:s3:::{aws_bucket}",+ },+ ],+ }++ 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 arndiff --git a/products/batch_exports/backend/tests/api/destination_tests/test_s3_destination_tests.py b/products/batch_exports/backend/tests/api/destination_tests/test_s3_destination_tests.pyindex 4f6d0340c883..a706a02ea41e 100644--- a/products/batch_exports/backend/tests/api/destination_tests/test_s3_destination_tests.py+++ b/products/batch_exports/backend/tests/api/destination_tests/test_s3_destination_tests.py@@ -3,14 +3,25 @@ import uuidimport pytestfrom django.conf import settings--from products.batch_exports.backend.api.destination_tests.s3 import S3EnsureBucketTestStep, Status+from django.test import override_settings++from products.batch_exports.backend.api.destination_tests import get_destination_test+from products.batch_exports.backend.api.destination_tests.s3 import (+ AwsS3DestinationTest,+ S3AssumeRoleTestStep,+ S3CompatibleDestinationTest,+ S3EnsureBucketTestStep,+ Status,+)from products.batch_exports.backend.tests.temporal.utils.s3 import create_test_client, delete_all_from_s3-pytestmark = [pytest.mark.asyncio]-TEST_ROOT_BUCKET = "test-destination-tests"+# Production destination tests use a single attempt (fast failure for users verifying+# config). These tests create a role and immediately assume it, so they need extra+# attempts to absorb IAM's eventual consistency.+ROLE_PROPAGATION_ATTEMPTS = 5+@pytest.fixturedef bucket_name(request) -> str:@@ -73,3 +84,150 @@ async def test_test_steps_fail_if_not_configured(step):result = await step.run()assert result.status == Status.FAILEDassert result.message == "The test step cannot run as it's not configured."+++ "kwargs,expected",+ [+ # Bucket plus long-lived credentials.+ ({"bucket_name": "b", "aws_access_key_id": "a", "aws_secret_access_key": "s"}, True),+ # Bucket plus role assumption.+ ({"bucket_name": "b", "aws_role_arn": "arn:aws:iam::123:role/r", "organization_id": "1"}, True),+ # Missing bucket.+ ({"aws_access_key_id": "a", "aws_secret_access_key": "s"}, False),+ # Bucket but no credentials at all.+ ({"bucket_name": "b"}, False),+ # Role without organization id can't build the external id, so it's not usable on its own.+ ({"bucket_name": "b", "aws_role_arn": "arn:aws:iam::123:role/r"}, False),+ ],+)+def test_ensure_bucket_step_is_configured(kwargs, expected):+ assert S3EnsureBucketTestStep(**kwargs)._is_configured() is expected+++async def test_assume_role_step_skips_without_role():+ """The assume role step is skipped (not failed) when no role is configured.++ This lets key-based AwsS3 exports run the rest of their steps.+ """+ test_step = S3AssumeRoleTestStep(aws_role_arn=None)+ result = await test_step.run()++ assert result.status == Status.SKIPPED+ assert result.message == "No configured AWS role ARN, skipping test"+++ "destination,expected_test,expected_steps",+ [+ ("S3", S3CompatibleDestinationTest, [S3EnsureBucketTestStep]),+ ("S3Compatible", S3CompatibleDestinationTest, [S3EnsureBucketTestStep]),+ ("AwsS3", AwsS3DestinationTest, [S3AssumeRoleTestStep, S3EnsureBucketTestStep]),+ ],+)+def test_get_destination_test_resolves_s3_family(destination, expected_test, expected_steps):+ destination_test = get_destination_test(destination=destination)++ assert isinstance(destination_test, expected_test)+ assert [type(step) for step in destination_test.steps] == expected_steps+++def test_aws_s3_destination_test_serializes_without_integration():+ """AwsS3 configured with inline credentials (no integration) must not raise.++ Its steps reference `organization_id` and each step needs an initialized+ `result`, so building the steps and serializing them exercises both.+ """+ destination_test = AwsS3DestinationTest()+ destination_test.configure(bucket_name="b", region="us-east-1", aws_access_key_id="a", aws_secret_access_key="s")++ assert destination_test.as_dict() == {+ "steps": [+ {"name": step.name, "description": step.description, "result": None} for step in destination_test.steps+ ]+ }+++async def test_assume_role_step_passes_with_assumable_role(+ external_aws_role_arn: str,+ destination_aws_role_arn: str,+ aorganization,+ bucket_name,+):+ """The assume role step passes when the role is assumable with the right external id."""+ test_step = S3AssumeRoleTestStep(+ aws_role_arn=destination_aws_role_arn,+ bucket_name=bucket_name,+ organization_id=aorganization.id,+ max_attempts=ROLE_PROPAGATION_ATTEMPTS,+ )++ with override_settings(BATCH_EXPORT_S3_EXTERNAL_ROLE_ARN=external_aws_role_arn):+ result = await test_step.run()++ assert result.status == Status.PASSED, result.message+ assert result.message is None++[email protected]("external_id", ["not-an-org-id"], indirect=True)+async def test_assume_role_step_fails_with_wrong_external_id(+ external_aws_role_arn: str,+ destination_aws_role_arn: str,+ external_id: str | None,+ bucket_name: str,+ aorganization,+):+ """A mismatched external id surfaces an AccessDenied failure."""+ test_step = S3AssumeRoleTestStep(+ aws_role_arn=destination_aws_role_arn, bucket_name=bucket_name, organization_id=aorganization.id+ )++ with override_settings(BATCH_EXPORT_S3_EXTERNAL_ROLE_ARN=external_aws_role_arn):+ result = await test_step.run()++ assert result.status == Status.FAILED+ assert result.message is not None+ assert "AccessDenied" in result.message++[email protected]("external_id", [None], indirect=True)+async def test_assume_role_step_fails_without_external_id_condition(+ external_aws_role_arn: str, destination_aws_role_arn: str, external_id: str | None, aorganization, bucket_name: str+):+ """A role whose trust policy omits the external id condition is rejected."""+ test_step = S3AssumeRoleTestStep(+ aws_role_arn=destination_aws_role_arn,+ bucket_name=bucket_name,+ organization_id=aorganization.id,+ max_attempts=ROLE_PROPAGATION_ATTEMPTS,+ )++ with override_settings(BATCH_EXPORT_S3_EXTERNAL_ROLE_ARN=external_aws_role_arn):+ result = await test_step.run()++ assert result.status == Status.FAILED+ assert result.message is not None+ assert "without a required external id condition" in result.message+++async def test_ensure_bucket_step_passes_with_role_assumption(+ external_aws_role_arn: str,+ destination_aws_role_arn: str,+ aws_bucket: str,+ region: str,+ aorganization,+):+ """The bucket check resolves temporary credentials via role assumption and passes."""+ test_step = S3EnsureBucketTestStep(+ bucket_name=aws_bucket,+ region=region,+ aws_role_arn=destination_aws_role_arn,+ organization_id=aorganization.id,+ max_attempts=ROLE_PROPAGATION_ATTEMPTS,+ )++ with override_settings(BATCH_EXPORT_S3_EXTERNAL_ROLE_ARN=external_aws_role_arn):+ result = await test_step.run()++ assert result.status == Status.PASSED+ assert result.message is Nonediff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/conftest.py b/products/batch_exports/backend/tests/temporal/destinations/s3/conftest.pyindex 948c62e19f34..32032ff7a38c 100644--- a/products/batch_exports/backend/tests/temporal/destinations/s3/conftest.py+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/conftest.py@@ -1,10 +1,7 @@import os-import jsonimport uuidimport typing-import asyncioimport secrets-import contextlibimport collections.abcimport pytest@@ -18,7 +15,7 @@ import botocore.exceptionsfrom posthog.temporal.tests.utils.models import acreate_batch_export, adelete_batch_export-from products.batch_exports.backend.tests.temporal.utils.s3 import create_test_client, delete_all_from_s3+from products.batch_exports.backend.tests.temporal.utils.s3 import aws_role, create_test_client, delete_all_from_s3if typing.TYPE_CHECKING:from types_aiobotocore_s3 import S3Client@@ -27,7 +24,6 @@ pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]LOGGER = structlog.get_logger()TEST_ROOT_BUCKET = "test-batch-exports"-ARN = strTEST_REGION = os.getenv("TEST_S3_BUCKET_REGION", "us-east-1")@@ -420,68 +416,3 @@ async def destination_aws_role_arn(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/utils/s3.py b/products/batch_exports/backend/tests/temporal/utils/s3.pyindex 798560960f6f..8a8a71b20f7a 100644--- a/products/batch_exports/backend/tests/temporal/utils/s3.py+++ b/products/batch_exports/backend/tests/temporal/utils/s3.py@@ -1,13 +1,20 @@import gzipimport json+import asyncioimport datetime as dtimport functools+import contextlib+import collections.abc++import pytestfrom django.conf import settingsimport brotliimport aioboto3+import structlogimport pyarrow.parquet as pq+import botocore.exceptionsfrom pyarrow import fsfrom types_aiobotocore_s3.client import S3Client@@ -16,10 +23,83 @@ from products.batch_exports.backend.temporal.destinations.s3_batch_export importFILE_FORMAT_EXTENSIONS,)+LOGGER = structlog.get_logger()+ARN = str+SESSION = aioboto3.Session()create_test_client = functools.partial(SESSION.client, endpoint_url=settings.OBJECT_STORAGE_ENDPOINT)+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]:+ """Create a temporary AWS IAM role for the duration of a test.++ The role is created with the provided trust and (optional) inline policy, and+ cleaned up on exit. Skips the test if AWS credentials or permissions are missing.+ """+ 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)++async def read_parquet_from_s3(s3_client: S3Client,bucket_name: str,