: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(managed-migrations): add IAM role auth for S3 batch imports (#73380)
Nick Bestacbe7e56fb79
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 2aa97bf21a83..99f12202030f 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -370,6 +370,7 @@ export const FEATURE_FLAGS = {LOGS_SPARKLINE_SERVICE_BREAKDOWN: 'logs-sparkline-service-breakdown', // owner: #team-logsLOGS_SQL_VIEW: 'logs-sql-view', // owner: #team-logsLOGS_TABBED_VIEW: 'logs-tabbed-view', // owner: #team-logs+ MANAGED_MIGRATIONS_IAM_ROLE_AUTH: 'managed-migrations-iam-role-auth', // owner: #team-ingestion, gates IAM role auth for S3 batch importsMANAGED_MIGRATIONS_TRIAL_RUNS: 'managed-migrations-trial-runs', // owner: #team-ingestion, gates trial runs for managed migrationsMANAGED_VIEWSETS: 'managed-viewsets', // owner: @rafaeelaudibert #team-revenue-analyticsMARKETING_ANALYTICS_AI: 'marketing-analytics-ai', // owner: @jabahamondes #team-web-analyticsdiff --git a/posthog/settings/managed_migrations.py b/posthog/settings/managed_migrations.pyindex 78eeaa592e1d..9a51a5907f05 100644--- a/posthog/settings/managed_migrations.py+++ b/posthog/settings/managed_migrations.py@@ -3,6 +3,8 @@ from typing import Optionalfrom posthog.settings.base_variables import DEBUG, TESTfrom posthog.settings.object_storage import OBJECT_STORAGE_REGION+from posthog.settings.utils import get_from_env+from posthog.utils import str_to_bool# S3-compatible store holding managed-migration trial run output (browsable# JSONL pages + summary), written by the batch-import worker (its TRIAL_BUCKET_*@@ -30,3 +32,13 @@ MANAGED_MIGRATIONS_TRIAL_S3_REGION = os.getenv("MANAGED_MIGRATIONS_TRIAL_S3_REGI# responds accordingly); set it wherever the worker fleet has a trial bucket.MANAGED_MIGRATIONS_TRIAL_S3_BUCKET = os.getenv("MANAGED_MIGRATIONS_TRIAL_S3_BUCKET", "posthog" if TEST or DEBUG else "")MANAGED_MIGRATIONS_TRIAL_S3_PREFIX = os.getenv("MANAGED_MIGRATIONS_TRIAL_S3_PREFIX", "trial_runs")++# ARN of the PostHog-owned IAM role the batch import worker runs as. Customers grant this+# role access to their S3 buckets via a cross-account trust policy, so it must stay stable.+MANAGED_MIGRATIONS_IMPORT_ROLE_ARN: str = os.getenv("MANAGED_MIGRATIONS_IMPORT_ROLE_ARN", "")++# Requires the Django pods to be allowed to assume MANAGED_MIGRATIONS_IMPORT_ROLE_ARN,+# so it stays off until that grant exists in the deployment.+MANAGED_MIGRATIONS_VALIDATE_ROLE_ON_CREATE: bool = get_from_env(+ "MANAGED_MIGRATIONS_VALIDATE_ROLE_ON_CREATE", False, type_cast=str_to_bool+)diff --git a/products/managed_migrations/backend/api/batch_imports.py b/products/managed_migrations/backend/api/batch_imports.pyindex fccb57556ec9..c3c29ca8c3e5 100644--- a/products/managed_migrations/backend/api/batch_imports.py+++ b/products/managed_migrations/backend/api/batch_imports.py@@ -1,11 +1,17 @@+import jsonimport uuidfrom copy import deepcopyfrom datetime import timedelta-from typing import cast+from typing import TYPE_CHECKING, cast+from django.conf import settingsfrom django.db import transaction+import boto3+import structlogimport posthoganalytics+from botocore.config import Config as BotoConfig+from botocore.exceptions import BotoCoreError, ClientErrorfrom django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_fieldfrom rest_framework import filters, serializers, status, viewsets@@ -16,6 +22,7 @@ from rest_framework.response import Responsefrom posthog.api.documentation import _FallbackSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializer+from posthog.exceptions_capture import capture_exceptionfrom posthog.models.user import Userfrom products.managed_migrations.backend import trial_storage@@ -24,8 +31,30 @@ from products.managed_migrations.backend.models.batch_imports import (BatchImportConfigBuilder,ContentType,DateRangeExportSource,+ get_aws_external_id,)+if TYPE_CHECKING:+ from posthog.models.team import Team++logger = structlog.get_logger(__name__)++S3_ROLE_ARN_REGEX = r"^arn:aws:iam::\d{12}:role\/[\w+=,.@\/-]+$"+++def _is_iam_role_auth_enabled(user: User, team: "Team") -> bool:+ return bool(+ posthoganalytics.feature_enabled(+ "managed-migrations-iam-role-auth",+ str(user.distinct_id),+ groups={"organization": str(team.organization_id), "project": str(team.id)},+ group_properties={"organization": {"id": str(team.organization_id)}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )++TRIAL_RECORD_LIMIT_DEFAULT = 1_000TRIAL_RECORD_LIMIT_MAX = 50_000@@ -121,23 +150,56 @@ class BatchImportSerializer(serializers.ModelSerializer):class BatchImportS3SourceCreateSerializer(BatchImportTrialOptionsMixin, BatchImportSerializer):- """Serializer for creating BatchImports with config builder methods"""+ """Serializer for creating BatchImports reading JSONL files from S3."""++ _builder_method = "from_s3"content_type = serializers.ChoiceField(choices=["mixpanel", "captured", "amplitude"],write_only=True,required=True,+ help_text="Format of the events in the source files.",)source_type = serializers.ChoiceField(choices=["s3"],write_only=True,required=True,+ help_text="Source storage type.",+ )+ s3_bucket = serializers.CharField(write_only=True, required=True, help_text="Name of the S3 bucket to import from.")+ s3_prefix = serializers.CharField(+ write_only=True,+ required=False,+ allow_blank=True,+ default="",+ help_text="Key prefix limiting which objects in the bucket are imported.",+ )+ s3_region = serializers.CharField(+ write_only=True, required=True, help_text="AWS region the bucket lives in, e.g. us-east-1."+ )+ access_key = serializers.CharField(+ write_only=True,+ required=False,+ allow_blank=True,+ help_text="AWS access key ID. Use together with secret_key; mutually exclusive with role_arn.",+ )+ secret_key = serializers.CharField(+ write_only=True,+ required=False,+ allow_blank=True,+ help_text="AWS secret access key. Use together with access_key; mutually exclusive with role_arn.",+ )+ role_arn = serializers.RegexField(+ regex=S3_ROLE_ARN_REGEX,+ write_only=True,+ required=False,+ allow_blank=True,+ help_text=(+ "ARN of an IAM role in your AWS account that trusts PostHog's import role. "+ "Recommended alternative to access keys; only works with AWS S3 (no custom endpoint_url). "+ "Fetch the trust policy to configure from the aws_iam_setup endpoint."+ ),)- s3_bucket = serializers.CharField(write_only=True, required=False)- s3_prefix = serializers.CharField(write_only=True, required=False, allow_blank=True)- s3_region = serializers.CharField(write_only=True, required=False)- access_key = serializers.CharField(write_only=True, required=False)- secret_key = serializers.CharField(write_only=True, required=False)endpoint_url = serializers.CharField(write_only=True,required=False,@@ -145,9 +207,15 @@ class BatchImportS3SourceCreateSerializer(BatchImportTrialOptionsMixin, BatchImpdefault=None,help_text="Custom endpoint URL for S3-compatible storage (e.g. Cloudflare R2, MinIO).",)- import_events = serializers.BooleanField(write_only=True, required=False, default=True)- generate_identify_events = serializers.BooleanField(write_only=True, required=False, default=True)- generate_group_identify_events = serializers.BooleanField(write_only=True, required=False, default=False)+ import_events = serializers.BooleanField(+ write_only=True, required=False, default=True, help_text="Whether to import regular events."+ )+ generate_identify_events = serializers.BooleanField(+ write_only=True, required=False, default=True, help_text="Whether to generate $identify events."+ )+ generate_group_identify_events = serializers.BooleanField(+ write_only=True, required=False, default=False, help_text="Whether to generate $groupidentify events."+ )class Meta:model = BatchImport@@ -167,6 +235,7 @@ class BatchImportS3SourceCreateSerializer(BatchImportTrialOptionsMixin, BatchImp"s3_region","access_key","secret_key",+ "role_arn","endpoint_url","import_events","generate_identify_events",@@ -185,129 +254,113 @@ class BatchImportS3SourceCreateSerializer(BatchImportTrialOptionsMixin, BatchImp"import_config",]- def create(self, validated_data: dict, **kwargs) -> BatchImport:- """Create BatchImport using config builder pattern."""- batch_import = BatchImport(- team_id=self.context["team_id"],- created_by_id=self.context["request"].user.id,- )+ def _is_iam_role_enabled(self) -> bool:+ return _is_iam_role_auth_enabled(self.context["request"].user, self.context["get_team"]())- content_type_map = {- "mixpanel": ContentType.MIXPANEL,- "amplitude": ContentType.AMPLITUDE,- "captured": ContentType.CAPTURED,- }+ def validate(self, data: dict) -> dict:+ data = super().validate(data)- content_type = content_type_map[validated_data["content_type"]]+ has_access_key = bool(data.get("access_key"))+ has_secret_key = bool(data.get("secret_key"))+ has_role = bool(data.get("role_arn"))- config_builder = batch_import.config.json_lines(content_type).from_s3(- bucket=validated_data["s3_bucket"],- prefix=validated_data.get("s3_prefix", ""),- region=validated_data["s3_region"],- access_key_id=validated_data["access_key"],- secret_access_key=validated_data["secret_key"],- endpoint_url=validated_data.get("endpoint_url"),- )+ if has_role and not (settings.MANAGED_MIGRATIONS_IMPORT_ROLE_ARN and self._is_iam_role_enabled()):+ raise serializers.ValidationError("IAM role authentication is not available for this project")- if content_type == ContentType.AMPLITUDE:- config_builder = (- config_builder.with_import_events(validated_data.get("import_events", True))- .with_generate_identify_events(validated_data.get("generate_identify_events", True))- .with_generate_group_identify_events(validated_data.get("generate_group_identify_events", False))+ if has_role and (has_access_key or has_secret_key):+ raise serializers.ValidationError("Provide either role_arn or access keys, not both")+ if has_access_key != has_secret_key:+ raise serializers.ValidationError(+ "Both access_key and secret_key are required for access key authentication")+ if not has_role and not has_access_key:+ raise serializers.ValidationError(+ "Authentication is required: provide role_arn (recommended) or access_key and secret_key"+ )+ if has_role and data.get("endpoint_url"):+ raise serializers.ValidationError(+ "IAM role authentication only works with AWS S3; S3-compatible storage must use access keys"+ )+ if (+ has_role+ and settings.MANAGED_MIGRATIONS_VALIDATE_ROLE_ON_CREATE+ and settings.MANAGED_MIGRATIONS_IMPORT_ROLE_ARN+ ):+ self._validate_role_access(data)- _apply_output_sink(config_builder, validated_data)-- batch_import.save()- return batch_import---class BatchImportS3GzipSourceCreateSerializer(BatchImportTrialOptionsMixin, BatchImportSerializer):- """Serializer for creating BatchImports with S3 gzipped JSONL source"""+ return data- content_type = serializers.ChoiceField(- choices=["mixpanel", "captured", "amplitude"],- write_only=True,- required=True,- )- source_type = serializers.ChoiceField(- choices=["s3_gzip"],- write_only=True,- required=True,- )- s3_bucket = serializers.CharField(write_only=True, required=False)- s3_prefix = serializers.CharField(write_only=True, required=False, allow_blank=True)- s3_region = serializers.CharField(write_only=True, required=False)- access_key = serializers.CharField(write_only=True, required=False)- secret_key = serializers.CharField(write_only=True, required=False)- endpoint_url = serializers.CharField(- write_only=True,- required=False,- allow_blank=True,- default=None,- help_text="Custom endpoint URL for S3-compatible storage (e.g. Cloudflare R2, MinIO).",- )- import_events = serializers.BooleanField(write_only=True, required=False, default=True)- generate_identify_events = serializers.BooleanField(write_only=True, required=False, default=True)- generate_group_identify_events = serializers.BooleanField(write_only=True, required=False, default=False)+ def _validate_role_access(self, data: dict) -> None:+ external_id = get_aws_external_id(self.context["get_team"]())+ boto_timeout = BotoConfig(connect_timeout=5, read_timeout=10)+ try:+ sts = boto3.client("sts", config=boto_timeout)+ import_role = sts.assume_role(+ RoleArn=settings.MANAGED_MIGRATIONS_IMPORT_ROLE_ARN,+ RoleSessionName="posthog-managed-migration-validation",+ DurationSeconds=900,+ )["Credentials"]+ except (ClientError, BotoCoreError) as err:+ # PostHog-side failure (our role grant or STS), not the customer's setup: skip+ # validation rather than block the create. The worker re-validates the full+ # chain and pauses the job with an actionable message if the role is broken.+ logger.exception("managed_migrations_import_role_assume_failed")+ capture_exception(err)+ return++ customer_sts = boto3.client(+ "sts",+ aws_access_key_id=import_role["AccessKeyId"],+ aws_secret_access_key=import_role["SecretAccessKey"],+ aws_session_token=import_role["SessionToken"],+ config=boto_timeout,+ )+ try:+ credentials = customer_sts.assume_role(+ RoleArn=data["role_arn"],+ RoleSessionName="posthog-managed-migration-validation",+ ExternalId=external_id,+ DurationSeconds=900,+ )["Credentials"]+ except (ClientError, BotoCoreError):+ raise serializers.ValidationError(+ "PostHog could not assume this IAM role. Verify the role exists, its trust policy "+ "allows PostHog's import role, and the External ID matches the one shown in setup."+ )- class Meta:- model = BatchImport- fields = [- "id",- "team_id",- "created_at",- "updated_at",- "state",- "status",- "display_status_message",- "import_config",- "content_type",- "source_type",- "s3_bucket",- "s3_prefix",- "s3_region",- "access_key",- "secret_key",- "endpoint_url",- "import_events",- "generate_identify_events",- "generate_group_identify_events",- "is_trial",- "trial_record_limit",- ]- read_only_fields = [- "id",- "team_id",- "created_at",- "updated_at",- "state",- "status",- "display_status_message",- "import_config",- ]+ s3 = boto3.client(+ "s3",+ region_name=data["s3_region"],+ aws_access_key_id=credentials["AccessKeyId"],+ aws_secret_access_key=credentials["SecretAccessKey"],+ aws_session_token=credentials["SessionToken"],+ config=boto_timeout,+ )+ try:+ s3.list_objects_v2(Bucket=data["s3_bucket"], Prefix=data.get("s3_prefix", ""), MaxKeys=1)+ except (ClientError, BotoCoreError):+ raise serializers.ValidationError(+ "The IAM role was assumed successfully, but listing the bucket failed. "+ "Check the role's s3:ListBucket and s3:GetObject permissions for this bucket and prefix."+ )def create(self, validated_data: dict, **kwargs) -> BatchImport:- """Create BatchImport using config builder pattern."""batch_import = BatchImport(team_id=self.context["team_id"],created_by_id=self.context["request"].user.id,)- content_type_map = {- "mixpanel": ContentType.MIXPANEL,- "amplitude": ContentType.AMPLITUDE,- "captured": ContentType.CAPTURED,- }-- content_type = content_type_map[validated_data["content_type"]]+ content_type = ContentType(validated_data["content_type"])+ role_arn = validated_data.get("role_arn") or None- config_builder = batch_import.config.json_lines(content_type).from_s3_gzip(+ config_builder = getattr(batch_import.config.json_lines(content_type), self._builder_method)(bucket=validated_data["s3_bucket"],prefix=validated_data.get("s3_prefix", ""),region=validated_data["s3_region"],- access_key_id=validated_data["access_key"],- secret_access_key=validated_data["secret_key"],+ access_key_id=validated_data.get("access_key") or None,+ secret_access_key=validated_data.get("secret_key") or None,+ role_arn=role_arn,+ external_id=get_aws_external_id(self.context["get_team"]()) if role_arn else None,endpoint_url=validated_data.get("endpoint_url"),)@@ -324,6 +377,19 @@ class BatchImportS3GzipSourceCreateSerializer(BatchImportTrialOptionsMixin, Batcreturn batch_import+class BatchImportS3GzipSourceCreateSerializer(BatchImportS3SourceCreateSerializer):+ """Serializer for creating BatchImports with S3 gzipped JSONL source."""++ _builder_method = "from_s3_gzip"++ source_type = serializers.ChoiceField(+ choices=["s3_gzip"],+ write_only=True,+ required=True,+ help_text="Source storage type.",+ )++class BatchImportDateRangeSourceCreateSerializer(BatchImportTrialOptionsMixin, BatchImportSerializer):"""Serializer for creating BatchImports with date range source (mixpanel, amplitude, etc.)"""@@ -571,6 +637,27 @@ class TrialRecordsResponseSerializer(serializers.Serializer):)+class BatchImportAWSIAMSetupSerializer(serializers.Serializer):+ """Values a customer needs to configure cross-account IAM role access for S3 imports."""++ available = serializers.BooleanField(+ help_text="Whether IAM role authentication is available on this PostHog deployment."+ )+ external_id = serializers.CharField(+ help_text="External ID to pin in the role trust policy's sts:ExternalId condition. Stable per project."+ )+ posthog_role_arn = serializers.CharField(+ allow_blank=True, help_text="ARN of PostHog's import role -- the principal your role must trust."+ )+ trust_policy = serializers.CharField(+ allow_blank=True, help_text="Ready-to-paste IAM trust policy JSON for the role in your AWS account."+ )+ permission_policy_template = serializers.CharField(+ allow_blank=True,+ help_text="IAM permission policy JSON template; replace YOUR_BUCKET and YOUR_PREFIX with your values.",+ )++class BatchImportViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"""Viewset for BatchImport model"""@@ -689,6 +776,77 @@ class BatchImportViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):response_serializer = BatchImportResponseSerializer(migration)return Response(response_serializer.data, status=status.HTTP_201_CREATED)+ def _is_iam_role_enabled_for_team(self) -> bool:+ return _is_iam_role_auth_enabled(cast(User, self.request.user), self.team)++ @extend_schema(+ responses={200: BatchImportAWSIAMSetupSerializer},+ description=(+ "Values needed to set up cross-account IAM role access for S3 imports: the external ID, "+ "PostHog's import role ARN, and ready-to-paste trust/permission policy JSON."+ ),+ )+ @action(methods=["GET"], detail=False)+ def aws_iam_setup(self, request: Request, **kwargs) -> Response:+ external_id = get_aws_external_id(self.team)+ posthog_role_arn = settings.MANAGED_MIGRATIONS_IMPORT_ROLE_ARN++ if not posthog_role_arn or not self._is_iam_role_enabled_for_team():+ serializer = BatchImportAWSIAMSetupSerializer(+ {+ "available": False,+ "external_id": external_id,+ "posthog_role_arn": "",+ "trust_policy": "",+ "permission_policy_template": "",+ }+ )+ return Response(serializer.data)++ trust_policy = json.dumps(+ {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Principal": {"AWS": posthog_role_arn},+ "Action": "sts:AssumeRole",+ "Condition": {"StringEquals": {"sts:ExternalId": external_id}},+ }+ ],+ },+ indent=2,+ )+ permission_policy_template = json.dumps(+ {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Action": ["s3:ListBucket"],+ "Resource": "arn:aws:s3:::YOUR_BUCKET",+ "Condition": {"StringLike": {"s3:prefix": ["YOUR_PREFIX*"]}},+ },+ {+ "Effect": "Allow",+ "Action": ["s3:GetObject"],+ "Resource": "arn:aws:s3:::YOUR_BUCKET/YOUR_PREFIX*",+ },+ ],+ },+ indent=2,+ )+ serializer = BatchImportAWSIAMSetupSerializer(+ {+ "available": True,+ "external_id": external_id,+ "posthog_role_arn": posthog_role_arn,+ "trust_policy": trust_policy,+ "permission_policy_template": permission_policy_template,+ }+ )+ return Response(serializer.data)+@action(methods=["POST"], detail=True)def pause(self, request: Request, **kwargs) -> Response:"""Pause a running batch import."""diff --git a/products/managed_migrations/backend/api/test/test_batch_imports.py b/products/managed_migrations/backend/api/test/test_batch_imports.pyindex 09ac125a8393..803397c49a04 100644--- a/products/managed_migrations/backend/api/test/test_batch_imports.py+++ b/products/managed_migrations/backend/api/test/test_batch_imports.py@@ -8,13 +8,19 @@ from django.contrib.messages import get_messagesfrom django.contrib.messages.middleware import MessageMiddlewarefrom django.contrib.sessions.middleware import SessionMiddlewarefrom django.http import HttpResponse-from django.test import RequestFactory+from django.test import RequestFactory, SimpleTestCase, override_settingsfrom parameterized import parameterizedfrom products.managed_migrations.backend import trial_storagefrom products.managed_migrations.backend.admin.batch_imports import BatchImportAdmin-from products.managed_migrations.backend.models.batch_imports import BatchImport, BatchImportConfigBuilder, ContentType+from products.managed_migrations.backend.api.batch_imports import BatchImportS3SourceCreateSerializer+from products.managed_migrations.backend.models.batch_imports import (+ BatchImport,+ BatchImportConfigBuilder,+ ContentType,+ get_aws_external_id,+)class TestBatchImportModel(BaseTest):@@ -401,6 +407,155 @@ class TestBatchImportConfigBuilder(BaseTest):}self.assertEqual(self.batch_import.import_config, expected_config)+ @parameterized.expand([("s3", "from_s3"), ("s3_gzip", "from_s3_gzip")])+ def test_from_s3_with_iam_role(self, _name, method):+ getattr(self.batch_import.config, method)(+ bucket="customer-bucket",+ prefix="events/",+ region="eu-west-1",+ role_arn="arn:aws:iam::123456789012:role/PostHogImport",+ external_id="posthog-us-test-uuid",+ )++ source = self.batch_import.import_config["source"]+ self.assertEqual(source["type"], _name)+ self.assertEqual(source["bucket"], "customer-bucket")+ self.assertEqual(source["role_arn"], "arn:aws:iam::123456789012:role/PostHogImport")+ self.assertEqual(source["external_id"], "posthog-us-test-uuid")+ self.assertNotIn("access_key_id_key", source)+ self.assertNotIn("secret_access_key_key", source)+ self.assertIsNone(self.batch_import.secrets)++ @parameterized.expand(+ [+ (+ "role_and_keys",+ {+ "role_arn": "arn:aws:iam::123456789012:role/R",+ "external_id": "ext",+ "access_key_id": "AK",+ "secret_access_key": "SK",+ },+ "Exactly one of access keys or role_arn",+ ),+ (+ "role_and_endpoint",+ {+ "role_arn": "arn:aws:iam::123456789012:role/R",+ "external_id": "ext",+ "endpoint_url": "http://minio:9000",+ },+ "only works with AWS S3",+ ),+ (+ "role_without_external_id",+ {"role_arn": "arn:aws:iam::123456789012:role/R"},+ "external_id is required",+ ),+ (+ "no_auth",+ {},+ "Exactly one of access keys or role_arn",+ ),+ ]+ )+ def test_from_s3_invalid_auth_combinations(self, _name, kwargs, expected_message):+ with self.assertRaisesRegex(ValueError, expected_message):+ self.batch_import.config.from_s3(+ bucket="b",+ prefix="",+ region="us-east-1",+ **kwargs,+ )+++@override_settings(MANAGED_MIGRATIONS_IMPORT_ROLE_ARN="arn:aws:iam::999999999999:role/PostHogBatchImport")+class TestBatchImportS3AuthValidation(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "role_only_valid",+ {"role_arn": "arn:aws:iam::123456789012:role/PostHogImport"},+ True,+ ),+ (+ "keys_only_valid",+ {"access_key": "AKIATEST", "secret_key": "secret123"},+ True,+ ),+ (+ "role_and_keys_rejected",+ {"role_arn": "arn:aws:iam::123456789012:role/R", "access_key": "AK", "secret_key": "SK"},+ False,+ ),+ (+ "role_and_endpoint_rejected",+ {"role_arn": "arn:aws:iam::123456789012:role/R", "endpoint_url": "http://minio:9000"},+ False,+ ),+ (+ "partial_keys_rejected",+ {"access_key": "AK"},+ False,+ ),+ (+ "no_auth_rejected",+ {},+ False,+ ),+ ]+ )+ @patch.object(BatchImportS3SourceCreateSerializer, "_is_iam_role_enabled", return_value=True)+ def test_auth_combination_validation(self, _name, auth_fields, should_be_valid, _mock_flag):+ data = {+ "source_type": "s3",+ "content_type": "captured",+ "s3_bucket": "test-bucket",+ "s3_region": "us-east-1",+ **auth_fields,+ }+ serializer = BatchImportS3SourceCreateSerializer(data=data)+ self.assertEqual(serializer.is_valid(), should_be_valid, serializer.errors)++ def test_invalid_role_arn_format_rejected(self):+ data = {+ "source_type": "s3",+ "content_type": "captured",+ "s3_bucket": "test-bucket",+ "s3_region": "us-east-1",+ "role_arn": "not-a-valid-arn",+ }+ serializer = BatchImportS3SourceCreateSerializer(data=data)+ self.assertFalse(serializer.is_valid())+ self.assertIn("role_arn", serializer.errors)++ @patch.object(BatchImportS3SourceCreateSerializer, "_is_iam_role_enabled", return_value=False)+ def test_role_arn_rejected_when_flag_off(self, _mock_flag):+ data = {+ "source_type": "s3",+ "content_type": "captured",+ "s3_bucket": "test-bucket",+ "s3_region": "us-east-1",+ "role_arn": "arn:aws:iam::123456789012:role/PostHogImport",+ }+ serializer = BatchImportS3SourceCreateSerializer(data=data)+ self.assertFalse(serializer.is_valid())+ self.assertIn("IAM role authentication is not available", str(serializer.errors))++ @patch.object(BatchImportS3SourceCreateSerializer, "_is_iam_role_enabled", return_value=True)+ def test_role_arn_rejected_when_import_role_unconfigured(self, _mock_flag):+ data = {+ "source_type": "s3",+ "content_type": "captured",+ "s3_bucket": "test-bucket",+ "s3_region": "us-east-1",+ "role_arn": "arn:aws:iam::123456789012:role/PostHogImport",+ }+ with override_settings(MANAGED_MIGRATIONS_IMPORT_ROLE_ARN=""):+ serializer = BatchImportS3SourceCreateSerializer(data=data)+ self.assertFalse(serializer.is_valid())+ self.assertIn("IAM role authentication is not available", str(serializer.errors))+class TestBatchImportAdminActions(BaseTest):def _request_with_messages(self):@@ -969,6 +1124,74 @@ class TestBatchImportAPI(APIBaseTest):self.assertEqual(response.status_code, 400)self.assertEqual(response.json()["attr"], "endpoint_url")+ @override_settings(MANAGED_MIGRATIONS_IMPORT_ROLE_ARN="arn:aws:iam::999999999999:role/PostHogBatchImport")+ @patch("products.managed_migrations.backend.api.batch_imports.posthoganalytics.feature_enabled", return_value=True)+ def test_s3_import_with_iam_role_creates_config_without_secrets(self, _mock_flag):+ response = self.client.post(+ f"/api/projects/{self.team.id}/managed_migrations",+ {+ "source_type": "s3",+ "content_type": "captured",+ "s3_bucket": "customer-bucket",+ "s3_region": "eu-west-1",+ "s3_prefix": "events/",+ "role_arn": "arn:aws:iam::123456789012:role/PostHogImport",+ },+ )++ self.assertEqual(response.status_code, 201, response.json())+ batch_import = BatchImport.objects.get(id=response.json()["id"])+ source = batch_import.import_config["source"]+ self.assertEqual(source["role_arn"], "arn:aws:iam::123456789012:role/PostHogImport")+ self.assertIn("external_id", source)+ self.assertNotIn("access_key_id_key", source)+ self.assertIsNone(batch_import.secrets)++ @patch("products.managed_migrations.backend.api.batch_imports.posthoganalytics.feature_enabled", return_value=False)+ def test_s3_import_with_role_rejected_when_flag_off(self, _mock_flag):+ response = self.client.post(+ f"/api/projects/{self.team.id}/managed_migrations",+ {+ "source_type": "s3",+ "content_type": "captured",+ "s3_bucket": "test-bucket",+ "s3_region": "us-east-1",+ "role_arn": "arn:aws:iam::123456789012:role/PostHogImport",+ },+ )++ self.assertEqual(response.status_code, 400)+ self.assertIn("not available", str(response.json()))++ @patch("products.managed_migrations.backend.api.batch_imports.posthoganalytics.feature_enabled", return_value=True)+ def test_aws_iam_setup_returns_policy_material(self, _mock_flag):+ with self.settings(MANAGED_MIGRATIONS_IMPORT_ROLE_ARN="arn:aws:iam::999999999999:role/PostHogBatchImport"):+ response = self.client.get(f"/api/projects/{self.team.id}/managed_migrations/aws_iam_setup")++ self.assertEqual(response.status_code, 200)+ data = response.json()+ self.assertTrue(data["available"])+ self.assertEqual(data["external_id"], get_aws_external_id(self.team))+ self.assertEqual(data["posthog_role_arn"], "arn:aws:iam::999999999999:role/PostHogBatchImport")+ self.assertIn("sts:AssumeRole", data["trust_policy"])+ self.assertIn("s3:GetObject", data["permission_policy_template"])++ @patch("products.managed_migrations.backend.api.batch_imports.posthoganalytics.feature_enabled", return_value=True)+ def test_aws_iam_setup_unavailable_without_role_arn_setting(self, _mock_flag):+ with self.settings(MANAGED_MIGRATIONS_IMPORT_ROLE_ARN=""):+ response = self.client.get(f"/api/projects/{self.team.id}/managed_migrations/aws_iam_setup")++ self.assertEqual(response.status_code, 200)+ self.assertFalse(response.json()["available"])++ @patch("products.managed_migrations.backend.api.batch_imports.posthoganalytics.feature_enabled", return_value=False)+ def test_aws_iam_setup_unavailable_when_flag_off(self, _mock_flag):+ with self.settings(MANAGED_MIGRATIONS_IMPORT_ROLE_ARN="arn:aws:iam::999999999999:role/PostHogBatchImport"):+ response = self.client.get(f"/api/projects/{self.team.id}/managed_migrations/aws_iam_setup")++ self.assertEqual(response.status_code, 200)+ self.assertFalse(response.json()["available"])+class TestBatchImportTrialAPI(APIBaseTest):S3_PAYLOAD = {diff --git a/products/managed_migrations/backend/models/batch_imports.py b/products/managed_migrations/backend/models/batch_imports.pyindex d96853d7c7f6..b4a4dd38ed88 100644--- a/products/managed_migrations/backend/models/batch_imports.py+++ b/products/managed_migrations/backend/models/batch_imports.py@@ -1,5 +1,5 @@from enum import Enum-from typing import Self+from typing import TYPE_CHECKING, Selffrom django.conf import settingsfrom django.db import models@@ -10,6 +10,14 @@ from posthog.models.utils import UUIDTModelfrom products.managed_migrations.backend.models.batch_import_utils import redact_part_key+if TYPE_CHECKING:+ from posthog.models.team import Team+++def get_aws_external_id(team: "Team") -> str:+ region = (settings.CLOUD_DEPLOYMENT or "dev").lower()+ return f"posthog-{region}-{team.uuid}"+class DateRangeExportSource(str, Enum):MIXPANEL = "mixpanel"@@ -171,7 +179,12 @@ class BatchImportConfigBuilder:self.batch_import = batch_importif initialize_empty:self.batch_import.import_config = {}+ self.batch_import.secrets = None++ def _store_secret(self, key: str, value: str | list[str]) -> None:+ if self.batch_import.secrets is None:self.batch_import.secrets = {}+ self.batch_import.secrets[key] = valuedef json_lines(self, content_type: ContentType, skip_blanks: bool = True) -> Self:self.batch_import.import_config["data_format"] = {@@ -194,28 +207,45 @@ class BatchImportConfigBuilder:"allow_internal_ips": allow_internal_ips,"timeout_seconds": timeout_seconds,}- self.batch_import.secrets[urls_key] = urls+ self._store_secret(urls_key, urls)return self- def from_s3(+ def _s3_source(self,+ source_type: str,bucket: str,prefix: str,region: str,- access_key_id: str,- secret_access_key: str,- endpoint_url: str | None = None,- access_key_id_key: str = "aws_access_key_id",- secret_access_key_key: str = "aws_secret_access_key",+ access_key_id: str | None,+ secret_access_key: str | None,+ role_arn: str | None,+ external_id: str | None,+ endpoint_url: str | None,+ access_key_id_key: str,+ secret_access_key_key: str,) -> Self:source: dict = {- "type": "s3",+ "type": source_type,"bucket": bucket,"prefix": prefix,"region": region,- "access_key_id_key": access_key_id_key,- "secret_access_key_key": secret_access_key_key,}+ if role_arn:+ if access_key_id is not None or secret_access_key is not None:+ raise ValueError("Exactly one of access keys or role_arn must be provided for S3 sources")+ if endpoint_url:+ raise ValueError("IAM role authentication only works with AWS S3 endpoints")+ if not external_id:+ raise ValueError("external_id is required for IAM role authentication")+ source["role_arn"] = role_arn+ source["external_id"] = external_id+ else:+ if access_key_id is None or secret_access_key is None:+ raise ValueError("Exactly one of access keys or role_arn must be provided for S3 sources")+ source["access_key_id_key"] = access_key_id_key+ source["secret_access_key_key"] = secret_access_key_key+ self._store_secret(access_key_id_key, access_key_id)+ self._store_secret(secret_access_key_key, secret_access_key)if endpoint_url:source["endpoint_url"] = endpoint_urlif settings.DEBUG:@@ -224,40 +254,61 @@ class BatchImportConfigBuilder:# non-public IPs otherwise. Never set outside DEBUG.source["allow_internal_ips"] = Trueself.batch_import.import_config["source"] = source- self.batch_import.secrets[access_key_id_key] = access_key_id- self.batch_import.secrets[secret_access_key_key] = secret_access_keyreturn self+ def from_s3(+ self,+ bucket: str,+ prefix: str,+ region: str,+ access_key_id: str | None = None,+ secret_access_key: str | None = None,+ role_arn: str | None = None,+ external_id: str | None = None,+ endpoint_url: str | None = None,+ access_key_id_key: str = "aws_access_key_id",+ secret_access_key_key: str = "aws_secret_access_key",+ ) -> Self:+ return self._s3_source(+ "s3",+ bucket,+ prefix,+ region,+ access_key_id,+ secret_access_key,+ role_arn,+ external_id,+ endpoint_url,+ access_key_id_key,+ secret_access_key_key,+ )+def from_s3_gzip(self,bucket: str,prefix: str,region: str,- access_key_id: str,- secret_access_key: str,+ access_key_id: str | None = None,+ secret_access_key: str | None = None,+ role_arn: str | None = None,+ external_id: str | None = None,endpoint_url: str | None = None,access_key_id_key: str = "aws_access_key_id",secret_access_key_key: str = "aws_secret_access_key",) -> Self:- source: dict = {- "type": "s3_gzip",- "bucket": bucket,- "prefix": prefix,- "region": region,- "access_key_id_key": access_key_id_key,- "secret_access_key_key": secret_access_key_key,- }- if endpoint_url:- source["endpoint_url"] = endpoint_url- if settings.DEBUG:- # Local dev: let custom endpoints point at the dev stack- # (SeaweedFS on localhost) — the worker's SSRF guard blocks- # non-public IPs otherwise. Never set outside DEBUG.- source["allow_internal_ips"] = True- self.batch_import.import_config["source"] = source- self.batch_import.secrets[access_key_id_key] = access_key_id- self.batch_import.secrets[secret_access_key_key] = secret_access_key- return self+ return self._s3_source(+ "s3_gzip",+ bucket,+ prefix,+ region,+ access_key_id,+ secret_access_key,+ role_arn,+ external_id,+ endpoint_url,+ access_key_id_key,+ secret_access_key_key,+ )def from_date_range(self,@@ -329,8 +380,8 @@ class BatchImportConfigBuilder:"base_url": base_url,**additional_config,}- self.batch_import.secrets[access_key_key] = access_key- self.batch_import.secrets[secret_key_key] = secret_key+ self._store_secret(access_key_key, access_key)+ self._store_secret(secret_key_key, secret_key)return selfdef to_stdout(self, as_json: bool = True) -> Self:diff --git a/products/managed_migrations/frontend/generated/api.schemas.ts b/products/managed_migrations/frontend/generated/api.schemas.tsindex c66ee9e344ac..74683a456c9b 100644--- a/products/managed_migrations/frontend/generated/api.schemas.ts+++ b/products/managed_migrations/frontend/generated/api.schemas.ts@@ -379,6 +379,22 @@ export interface TrialRecordsResponseApi {summary: unknown}+/**+ * Values a customer needs to configure cross-account IAM role access for S3 imports.+ */+export interface BatchImportAWSIAMSetupApi {+ /** Whether IAM role authentication is available on this PostHog deployment. */+ available: boolean+ /** External ID to pin in the role trust policy's sts:ExternalId condition. Stable per project. */+ external_id: string+ /** ARN of PostHog's import role -- the principal your role must trust. */+ posthog_role_arn: string+ /** Ready-to-paste IAM trust policy JSON for the role in your AWS account. */+ trust_policy: string+ /** IAM permission policy JSON template; replace YOUR_BUCKET and YOUR_PREFIX with your values. */+ permission_policy_template: string+}+export type ManagedMigrationsSupportListParams = {/*** Number of results to return per page.diff --git a/products/managed_migrations/frontend/generated/api.ts b/products/managed_migrations/frontend/generated/api.tsindex 989fe4b60d3f..6dad661d989d 100644--- a/products/managed_migrations/frontend/generated/api.ts+++ b/products/managed_migrations/frontend/generated/api.ts@@ -9,6 +9,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ BatchImportAWSIAMSetupApi,BatchImportApi,BatchImportResponseApi,BatchImportSupportDetailApi,@@ -302,3 +303,20 @@ export const managedMigrationsTrialRecordsRetrieve = async (method: 'GET',})}++export const getManagedMigrationsAwsIamSetupRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/managed_migrations/aws_iam_setup/`+}++/**+ * Values needed to set up cross-account IAM role access for S3 imports: the external ID, PostHog's import role ARN, and ready-to-paste trust/permission policy JSON.+ */+export const managedMigrationsAwsIamSetupRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<BatchImportAWSIAMSetupApi> => {+ return apiMutator<BatchImportAWSIAMSetupApi>(getManagedMigrationsAwsIamSetupRetrieveUrl(projectId), {+ ...options,+ method: 'GET',+ })+}diff --git a/products/managed_migrations/mcp/tools.yaml b/products/managed_migrations/mcp/tools.yamlindex 2c228ab2d606..85d6809ee130 100644--- a/products/managed_migrations/mcp/tools.yaml+++ b/products/managed_migrations/mcp/tools.yaml@@ -9,6 +9,9 @@ feature: managed_migrationsurl_prefix: /managed_migrationsui_apps: {}tools:+ managed-migrations-aws-iam-setup-retrieve:+ operation: managed_migrations_aws_iam_setup_retrieve+ enabled: falsemanaged-migrations-create:operation: managed_migrations_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 25982ccbdda9..6ba394665dd1 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -11376,6 +11376,22 @@ export namespace Schemas {readonly import_config: unknown;}+ /**+ * Values a customer needs to configure cross-account IAM role access for S3 imports.+ */+ export interface BatchImportAWSIAMSetup {+ /** Whether IAM role authentication is available on this PostHog deployment. */+ available: boolean;+ /** External ID to pin in the role trust policy's sts:ExternalId condition. Stable per project. */+ external_id: string;+ /** ARN of PostHog's import role -- the principal your role must trust. */+ posthog_role_arn: string;+ /** Ready-to-paste IAM trust policy JSON for the role in your AWS account. */+ trust_policy: string;+ /** IAM permission policy JSON template; replace YOUR_BUCKET and YOUR_PREFIX with your values. */+ permission_policy_template: string;+ }+export interface BatchImportPartsProgress {/** Number of finished parts (a part is done when its committed byte offset has reached its known total size). */done: number;