Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(redshift-batch-export): Support integration models (#86497)

Tomás Farías Santanafd45cbfe4de2
diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.py
index ae78fbb52d8e..af8043ce48f9 100644
--- a/products/batch_exports/backend/service.py
+++ b/products/batch_exports/backend/service.py
@@ -29,6 +29,7 @@ from temporalio.client import (
from posthog.hogql.database.database import Database
from posthog.hogql.hogql import HogQLContext
+from posthog.dataclasses import frozen
from posthog.temporal.common.client import sync_connect
from posthog.temporal.common.schedule import (
a_pause_schedule,
@@ -400,6 +401,7 @@ class PostgresBatchExportInputs(BaseBatchExportInputs):
IAMRole = str
+IntegrationID = int
@dataclass(frozen=False)
@@ -417,27 +419,27 @@ class AWSCredentials:
return self.expiration.isoformat()
-@dataclass
+@frozen
class RedshiftCopyInputs:
s3_bucket: str
region_name: str
s3_key_prefix: str
- # Authorization role or credentials for Redshift to COPY data from bucket.
- authorization: IAMRole | AWSCredentials
- # S3 batch export credentials.
- # TODO: Also support RBAC for S3 batch export, then we could take
- # `IAMRole | AWSCredentials` here too.
- bucket_credentials: AWSCredentials
+ # Authorization for Redshift to COPY data from the bucket: an IAM role ARN,
+ # inline credentials, or the id of a team-scoped aws-s3 integration.
+ authorization: IAMRole | AWSCredentials | IntegrationID
+ # Credentials used to stage files in the S3 bucket: inline credentials or
+ # the id of a team-scoped aws-s3 integration.
+ bucket_credentials: AWSCredentials | IntegrationID
@dataclass(frozen=False, kw_only=True)
class RedshiftBatchExportInputs(BaseBatchExportInputs):
"""Inputs for Redshift export workflow."""
- user: str
- password: str = field(repr=False)
- host: str
database: str
+ user: str | None = None
+ password: str | None = field(default=None, repr=False)
+ host: str | None = None
schema: str = "public"
table_name: str = "events"
port: int = 5439
@@ -459,17 +461,31 @@ class RedshiftBatchExportInputs(BaseBatchExportInputs):
else:
raise TypeError(f"Invalid type for copy inputs: '{type(self.copy_inputs)}'")
- bucket_credentials = AWSCredentials(
- aws_access_key_id=raw_inputs["bucket_credentials"]["aws_access_key_id"],
- aws_secret_access_key=raw_inputs["bucket_credentials"]["aws_secret_access_key"],
- )
+ # `BatchExportDestination.config` is an `EncryptedJSONField`, which stringifies scalar
+ # leaves on the decrypt round trip: an integration id saved as an int reads back as a
+ # numeric string, so both forms must be accepted here.
+ raw_bucket_credentials = raw_inputs["bucket_credentials"]
+ bucket_credentials: AWSCredentials | IntegrationID
+ if isinstance(raw_bucket_credentials, IntegrationID):
+ bucket_credentials = raw_bucket_credentials
+ elif isinstance(raw_bucket_credentials, str) and raw_bucket_credentials.isdigit():
+ bucket_credentials = IntegrationID(raw_bucket_credentials)
+ else:
+ bucket_credentials = AWSCredentials(
+ aws_access_key_id=raw_bucket_credentials["aws_access_key_id"],
+ aws_secret_access_key=raw_bucket_credentials["aws_secret_access_key"],
+ )
- if isinstance(raw_inputs["authorization"], str):
- authorization: IAMRole | AWSCredentials = raw_inputs["authorization"]
+ raw_authorization = raw_inputs["authorization"]
+ authorization: IAMRole | AWSCredentials | IntegrationID
+ if isinstance(raw_authorization, IntegrationID):
+ authorization = raw_authorization
+ elif isinstance(raw_authorization, str):
+ authorization = IntegrationID(raw_authorization) if raw_authorization.isdigit() else raw_authorization
else:
authorization = AWSCredentials(
- aws_access_key_id=raw_inputs["authorization"]["aws_access_key_id"],
- aws_secret_access_key=raw_inputs["authorization"]["aws_secret_access_key"],
+ aws_access_key_id=raw_authorization["aws_access_key_id"],
+ aws_secret_access_key=raw_authorization["aws_secret_access_key"],
)
self.copy_inputs = RedshiftCopyInputs(
diff --git a/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py b/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py
index 01ca44b76917..0242cd8244c6 100644
--- a/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py
@@ -3,6 +3,7 @@ import json
import typing
import asyncio
import datetime as dt
+import functools
import posixpath
import contextlib
import dataclasses
@@ -12,6 +13,7 @@ from django.conf import settings
import psycopg
import pyarrow as pa
+import aioboto3
import botocore.exceptions
from psycopg import sql
from structlog.contextvars import bind_contextvars
@@ -20,7 +22,18 @@ from temporalio.common import RetryPolicy
from posthog.dataclasses import frozen
from posthog.models import Team
-from posthog.models.integration import TLS, Authority, Credentials
+from posthog.models.integration import (
+ TLS,
+ Authority,
+ AWSRedshiftIntegration,
+ AWSRedshiftRoleBasedIntegration,
+ AWSS3Integration,
+ AWSS3RoleBasedIntegration,
+ Credentials,
+ Integration,
+ IntegrationError,
+ RedshiftIntegration,
+)
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.logger import get_logger, get_write_only_logger
@@ -32,6 +45,7 @@ from products.batch_exports.backend.service import (
BatchExportModel,
BatchExportSchema,
IAMRole,
+ IntegrationID,
RedshiftBatchExportInputs,
)
from products.batch_exports.backend.temporal.batch_exports import (
@@ -45,10 +59,12 @@ from products.batch_exports.backend.temporal.destinations.postgres_batch_export
Fields,
PostgreSQLClient,
PostgreSQLField,
+ _PostgreSQLClientInputsProtocol,
)
from products.batch_exports.backend.temporal.destinations.s3_batch_export import (
ConcurrentS3Consumer,
PolicyStatement,
+ RefreshCoroutine,
get_credentials_using_user_aws_role,
s3_client,
)
@@ -71,8 +87,10 @@ from products.batch_exports.backend.temporal.utils import (
LOGGER = get_write_only_logger(__name__)
EXTERNAL_LOGGER = get_logger()
-
NON_RETRYABLE_ERROR_TYPES = (
+ # The integration backing this export is missing, of the wrong kind, or
+ # misconfigured. Retrying can never recover it.
+ "IntegrationError",
# Raised on errors that are related to database operation.
# For example: unexpected disconnect, database or other object not found.
"OperationalError",
@@ -505,6 +523,13 @@ class RedshiftClient(PostgreSQLClient):
secret_access_key=sql.Literal(authorization.aws_secret_access_key),
)
+ if authorization.aws_session_token is not None:
+ credentials += sql.SQL(
+ """
+ SESSION_TOKEN {session_token}
+ """
+ ).format(session_token=sql.Literal(authorization.aws_session_token))
+
else:
if authorization == "default":
credentials = sql.SQL("IAM_ROLE default")
@@ -632,18 +657,18 @@ def get_redshift_fields_from_record_schema(
return pg_schema
+@frozen
class S3StageBucketParameters:
name: str
region_name: str
- credentials: IAMRole | AWSCredentials
+ credentials: IAMRole | AWSCredentials | IntegrationID
+@frozen
class CopyParameters:
s3_bucket: S3StageBucketParameters
s3_key_prefix: str
- authorization: IAMRole | AWSCredentials
+ authorization: IAMRole | AWSCredentials | IntegrationID
@frozen
@@ -669,6 +694,18 @@ class ConnectionParameters:
return TLS(ssl_mode="prefer" if settings.TEST else "require")
+@frozen
+class ServerConnectionParameters:
+ """Location of a Redshift server for exports whose credentials live in an integration.
+
+ `host` is None when a plain Redshift integration carries the host itself.
+ """
+
+ database: str
+ port: int
+ host: str | None = None
+
+
@dataclasses.dataclass
class TableParameters:
schema_name: str
@@ -676,23 +713,25 @@ class TableParameters:
properties_data_type: str = "varchar"
+@frozen
class RedshiftCopyActivityInputs:
"""Inputs for Redshift copy activity."""
batch_export: BatchExportInsertInputs
- connection: ConnectionParameters
+ connection: ConnectionParameters | ServerConnectionParameters
table: TableParameters
copy: CopyParameters
+ integration_id: IntegrationID | None = None
+@frozen
class RedshiftInsertInputs:
"""Inputs for Redshift insert activity."""
batch_export: BatchExportInsertInputs
- connection: ConnectionParameters
+ connection: ConnectionParameters | ServerConnectionParameters
table: TableParameters
+ integration_id: IntegrationID | None = None
class RedshiftConsumer(Consumer):
@@ -877,6 +916,335 @@ def _get_merge_settings(
return NotRequiredMergeSettings(requires_merge=False)
+async def _get_redshift_integration(
+ integration_id: int, team_id: int
+) -> AWSRedshiftRoleBasedIntegration | AWSRedshiftIntegration | RedshiftIntegration:
+ """Fetch a Redshift integration from the database."""
+ try:
+ integration = await Integration.objects.aget(id=integration_id, team_id=team_id)
+ except Integration.DoesNotExist:
+ raise IntegrationError(f"Redshift integration with ID '{integration_id}' not found for team '{team_id}'")
+
+ if integration.kind != Integration.IntegrationKind.AWS_REDSHIFT:
+ raise IntegrationError(
+ f"Integration with ID '{integration_id}' for team '{team_id}' is not a Redshift integration "
+ f"(kind='{integration.kind}')"
+ )
+ if "aws_role_arn" in integration.config:
+ return AWSRedshiftRoleBasedIntegration(integration)
+ elif "aws_access_key_id" in integration.sensitive_config:
+ return AWSRedshiftIntegration(integration)
+ else:
+ return RedshiftIntegration(integration)
+
+
+async def _get_aws_s3_integration(integration_id: int, team_id: int) -> AWSS3RoleBasedIntegration | AWSS3Integration:
+ """Fetch an AWS S3 integration from the database."""
+ try:
+ integration = await Integration.objects.aget(id=integration_id, team_id=team_id)
+ except Integration.DoesNotExist:
+ raise IntegrationError(f"AWS S3 integration with ID '{integration_id}' not found for team '{team_id}'")
+
+ if integration.kind != Integration.IntegrationKind.AWS_S3:
+ raise IntegrationError(
+ f"Integration with ID '{integration_id}' for team '{team_id}' is not an S3 integration "
+ f"(kind='{integration.kind}')"
+ )
+ if "aws_role_arn" in integration.config:
+ return AWSS3RoleBasedIntegration(integration)
+ else:
+ return AWSS3Integration(integration)
+
+
+@frozen
+class RedshiftCredentials:
+ user: str
+ password: str = dataclasses.field(repr=False)
+
+
+@frozen
+class ProvisionedCluster:
+ """A provisioned Redshift cluster parsed from its endpoint hostname."""
+
+ cluster_identifier: str
+ region: str
+
+
+@frozen
+class ServerlessWorkgroup:
+ """A Redshift Serverless workgroup parsed from its endpoint hostname."""
+
+ workgroup: str
+ account_id: str
+ region: str
+
+
+def _parse_redshift_host(host: str) -> ProvisionedCluster | ServerlessWorkgroup:
+ """Parse a Redshift endpoint hostname into its cluster or workgroup location."""
+ match host.split(".", maxsplit=3):
+ case [cluster_identifier, _, region, "redshift.amazonaws.com"]:
+ return ProvisionedCluster(cluster_identifier=cluster_identifier, region=region)
+ case [workgroup, account_id, region, "redshift-serverless.amazonaws.com"]:
+ return ServerlessWorkgroup(workgroup=workgroup, account_id=account_id, region=region)
+ case _:
+ raise IntegrationError(
+ f"Redshift host '{host}' is not a recognized AWS Redshift endpoint. Expected "
+ "'<cluster>.<id>.<region>.redshift.amazonaws.com' or "
+ "'<workgroup>.<account>.<region>.redshift-serverless.amazonaws.com'"
+ )
+
+
+def _get_host_from_connection(connection: ConnectionParameters | ServerConnectionParameters) -> str:
+ if connection.host is None:
+ raise IntegrationError(
+ "An AWS Redshift integration requires the cluster endpoint to be set as 'host' in the "
+ "batch export configuration"
+ )
+ return connection.host
+
+
+async def _get_temporary_redshift_credentials(
+ aws_credentials: AWSCredentials,
+ *,
+ server: ProvisionedCluster | ServerlessWorkgroup,
+ user: str,
+ database: str,
+ auto_create: bool | None = None,
+ groups: list[str] | None = None,
+) -> RedshiftCredentials:
+ """Use AWS APIs to obtain temporary Redshift credentials.
+
+ This will return a username and password to be used to authenticate to
+ Redshift. Note that the returned user will be the same as user but it will
+ include the prefix IAM: or IAMA: (depending on the value of `auto_create`).
+ This prefix must be preserved when authenticating.
+
+ If auto_create is True, then the user or role given by aws_credentials must
+ also be allowed to redshift:CreateClusterUser on the dbuser resource. If the
+ user already exists then no new users will be created, even if
+ auto_create=True.
+
+ Automatically created users do not have any permissions. Thus, usually
+ groups should be set when auto_create=True. This parameter indicates which
+ groups is the user meant to join on creation, which is usually needed when
+ the user is automatically created. However, this is not a strict
+ requirement.
+
+ The AWS role or user requires redshift:JoinGroup on each dbgroup resource
+ whenever groups is set.
+
+ Serverless workgroups use `redshift-serverless:GetCredentials` instead of
+ `redshift:GetClusterCredentials`. There, the database user is derived from
+ the IAM identity, so `user`, `auto_create`, and `groups` do not apply.
+ """
+ session = aioboto3.Session(
+ aws_access_key_id=aws_credentials.aws_access_key_id,
+ aws_secret_access_key=aws_credentials.aws_secret_access_key,
+ aws_session_token=aws_credentials.aws_session_token,
+ )
+
+ match server:
+ case ProvisionedCluster():
+ optional: dict[str, typing.Any] = {}
+ if auto_create is not None:
+ optional["AutoCreate"] = auto_create
+ if groups is not None:
+ optional["DbGroups"] = groups
+
+ async with session.client("redshift", region_name=server.region) as redshift:
+ response = await redshift.get_cluster_credentials(
+ DbUser=user,
+ DbName=database,
+ ClusterIdentifier=server.cluster_identifier,
+ # TODO: Refreshable credentials
+ DurationSeconds=3600,
+ **optional,
+ )
+
+ return RedshiftCredentials(user=response["DbUser"], password=response["DbPassword"])
+
+ case ServerlessWorkgroup():
+ async with session.client("redshift-serverless", region_name=server.region) as redshift_serverless:
+ response = await redshift_serverless.get_credentials(
+ workgroupName=server.workgroup,
+ dbName=database,
+ durationSeconds=3600,
+ )
+
+ return RedshiftCredentials(user=response["dbUser"], password=response["dbPassword"])
+
+ case _:
+ typing.assert_never(server)
+
+
+async def _get_redshift_client_inputs(
+ inputs: RedshiftInsertInputs | RedshiftCopyActivityInputs,
+) -> _PostgreSQLClientInputsProtocol:
+ """Return PostgreSQL client inputs to establish a connection from Redshift.
+
+ The inputs will be obtained from an integration when integration_id is set,
+ and otherwise we will assert they are present in the activity inputs to be
+ read directly.
+ """
+ if inputs.integration_id is not None:
+ integration = await _get_redshift_integration(inputs.integration_id, inputs.batch_export.team_id)
+ return await _get_redshift_client_inputs_from_integration(integration, inputs)
+
+ if not isinstance(inputs.connection, ConnectionParameters):
+ raise IntegrationError(
+ "Redshift connection credentials are missing: the batch export has no linked integration "
+ "and no inline user and password configured"
+ )
+
+ return inputs.connection
+
+
+def _get_redshift_credentials_policy_statements(
+ integration: AWSRedshiftRoleBasedIntegration,
+ server: ProvisionedCluster | ServerlessWorkgroup,
+ database: str,
+) -> list[PolicyStatement]:
+ """Build policy statements scoping an assumed role to obtaining Redshift credentials."""
+ match server:
+ case ProvisionedCluster():
+ account_id = integration.aws_account_id
+ get_cluster_credentials_policy = PolicyStatement(
+ Effect="Allow",
+ Action=["redshift:GetClusterCredentials"],
+ Resource=[
+ f"arn:aws:redshift:{server.region}:{account_id}:dbuser:{server.cluster_identifier}/{integration.user}",
+ f"arn:aws:redshift:{server.region}:{account_id}:dbname:{server.cluster_identifier}/{database}",
+ ],
+ )
+ if integration.auto_create is True:
+ get_cluster_credentials_policy["Action"].append("redshift:CreateClusterUser")
+
+ policy_statements = [get_cluster_credentials_policy]
+ if integration.groups is not None:
+ policy_statements.append(
+ PolicyStatement(
+ Effect="Allow",
+ Action=["redshift:JoinGroup"],
+ Resource=[
+ f"arn:aws:redshift:{server.region}:{account_id}:dbgroup:{server.cluster_identifier}/{group}"
+ for group in integration.groups
+ ],
+ )
+ )
+ return policy_statements
+
+ case ServerlessWorkgroup():
+ # Workgroup ARNs contain a UUID that cannot be derived from the endpoint hostname,
+ # so Serverless requires the ARN on the integration to scope the policy exactly.
+ workgroup_arn = integration.workgroup_arn
+ if workgroup_arn is None:
+ raise IntegrationError(
+ "A Redshift Serverless workgroup requires 'workgroup_arn' to be set on the integration"
+ )
+
+ _, _, _, arn_region, arn_account_id, _ = workgroup_arn.split(":", maxsplit=5)
+ if arn_region != server.region or arn_account_id != server.account_id:
+ raise IntegrationError(
+ f"The integration's workgroup ARN '{workgroup_arn}' does not match the region or account "
+ f"of the Redshift Serverless host (region '{server.region}', account '{server.account_id}')"
+ )
+
+ return [
+ PolicyStatement(
+ Effect="Allow",
+ Action=["redshift-serverless:GetCredentials"],
+ Resource=[workgroup_arn],
+ )
+ ]
+
+ case _:
+ typing.assert_never(server)
+
+
+async def _get_redshift_client_inputs_from_integration(
+ integration: AWSRedshiftRoleBasedIntegration | AWSRedshiftIntegration | RedshiftIntegration,
+ inputs: RedshiftInsertInputs | RedshiftCopyActivityInputs,
+) -> _PostgreSQLClientInputsProtocol:
+ """Return PostgreSQL client inputs to establish a connection from Redshift.
+
+ These inputs can be obtained from an integration by:
+ * Generating temporary credentials using a short-lived session via assuming
+ a role configured in an integration.
+ * Generating temporary credentials using long-lived AWS credentials stored
+ in the integration.
+ * Directly reading inputs stored in the integration.
+
+ Depending on the type of integration, is which one we'll use.
+ """
+ client_inputs: _PostgreSQLClientInputsProtocol
+
+ match integration:
+ case AWSRedshiftRoleBasedIntegration():
+ host = _get_host_from_connection(inputs.connection)
+ server = _parse_redshift_host(host)
+
+ team = await Team.objects.aget(id=inputs.batch_export.team_id)
+ external_id = f"posthog-{team.organization_id}"
+
+ policy_statements = _get_redshift_credentials_policy_statements(
+ integration, server, inputs.connection.database
+ )
+
+ credentials = await get_credentials_using_user_aws_role(
+ integration.aws_role_arn,
+ external_id,
+ session_name=f"PostHog-batch-exports-{inputs.batch_export.batch_export_id}",
+ policy_statements=policy_statements,
+ )
+
+ redshift_credentials = await _get_temporary_redshift_credentials(
+ credentials,
+ server=server,
+ user=integration.user,
+ database=inputs.connection.database,
+ groups=integration.groups,
+ auto_create=integration.auto_create,
+ )
+ client_inputs = ConnectionParameters(
+ user=redshift_credentials.user,
+ password=redshift_credentials.password,
+ host=host,
+ port=inputs.connection.port,
+ database=inputs.connection.database,
+ )
+
+ case AWSRedshiftIntegration():
+ host = _get_host_from_connection(inputs.connection)
+ server = _parse_redshift_host(host)
+
+ redshift_credentials = await _get_temporary_redshift_credentials(
+ AWSCredentials(
+ aws_access_key_id=integration.aws_access_key_id,
+ aws_secret_access_key=integration.aws_secret_access_key,
+ ),
+ server=server,
+ user=integration.user,
+ database=inputs.connection.database,
+ groups=integration.groups,
+ auto_create=integration.auto_create,
+ )
+ client_inputs = ConnectionParameters(
+ user=redshift_credentials.user,
+ password=redshift_credentials.password,
+ host=host,
+ port=inputs.connection.port,
+ database=inputs.connection.database,
+ )
+
+ case RedshiftIntegration():
+ client_inputs = integration
+
+ case _:
+ typing.assert_never(integration)
+
+ return client_inputs
+
+
@activity.defn
@handle_non_retryable_errors(NON_RETRYABLE_ERROR_TYPES)
async def insert_into_redshift_activity_from_stage(inputs: RedshiftInsertInputs) -> BatchExportResult:
@@ -906,6 +1274,7 @@ async def insert_into_redshift_activity_from_stage(inputs: RedshiftInsertInputs)
bind_contextvars(
team_id=inputs.batch_export.team_id,
destination="Redshift",
+ integration_id=inputs.integration_id,
data_interval_start=inputs.batch_export.data_interval_start,
data_interval_end=inputs.batch_export.data_interval_end,
database=inputs.connection.database,
@@ -969,8 +1338,10 @@ async def insert_into_redshift_activity_from_stage(inputs: RedshiftInsertInputs)
else inputs.table.name
)
+ client_inputs = await _get_redshift_client_inputs(inputs)
+
async with RedshiftClient.from_inputs(
- inputs.connection, database=inputs.connection.database
+ client_inputs, database=inputs.connection.database
).connect() as redshift_client:
remove_duplicates = True
# filter out fields that are not in the destination table
@@ -1055,6 +1426,7 @@ async def upload_manifest_file(
credentials: AWSCredentials,
files_uploaded: list[str],
manifest_key: str,
+ refresh_using: RefreshCoroutine | None = None,
):
"""Upload manifest file used by Redshift COPY.
@@ -1070,6 +1442,7 @@ async def upload_manifest_file(
region=region_name,
# Required for unit tests which run against a local bucket, otherwise always None.
endpoint_url=settings.OBJECT_STORAGE_ENDPOINT if settings.TEST else None,
+ refresh_using=refresh_using,
) as client:
entries = []
@@ -1143,6 +1516,7 @@ async def delete_uploaded_files(
credentials: AWSCredentials,
files_uploaded: list[str],
manifest_key: str,
+ refresh_using: RefreshCoroutine | None = None,
):
"""Delete files uploaded to S3 bucket during 'COPY' activity.
@@ -1154,6 +1528,7 @@ async def delete_uploaded_files(
async with s3_client(
credentials,
region=region_name,
+ refresh_using=refresh_using,
) as client:
async def delete_key(f: str):
@@ -1174,6 +1549,7 @@ async def is_s3_read_access_denied(
region_name: str,
credentials: AWSCredentials,
keys: collections.abc.Sequence[str],
+ refresh_using: RefreshCoroutine | None = None,
) -> bool:
"""Return True only if a HEAD positively confirms read access is denied for any of `keys`.
@@ -1188,6 +1564,7 @@ async def is_s3_read_access_denied(
async with s3_client(
credentials,
region=region_name,
+ refresh_using=refresh_using,
) as client:
for key in keys:
try:
@@ -1210,6 +1587,7 @@ async def check_and_raise_redshift_copy_error(
region_name: str,
manifest_key: str,
files_uploaded: collections.abc.Sequence[str],
+ refresh_using: RefreshCoroutine | None = None,
) -> None:
"""Translate a failed Redshift COPY into an actionable error.
@@ -1227,7 +1605,11 @@ async def check_and_raise_redshift_copy_error(
if isinstance(authorization, AWSCredentials):
probe_keys = [manifest_key, *files_uploaded[:1]]
if await is_s3_read_access_denied(
- bucket=bucket, region_name=region_name, credentials=authorization, keys=probe_keys
+ bucket=bucket,
+ region_name=region_name,
+ credentials=authorization,
+ keys=probe_keys,
+ refresh_using=refresh_using,
):
raise InsufficientS3PermissionsError(bucket) from err
return
@@ -1243,6 +1625,119 @@ async def check_and_raise_redshift_copy_error(
raise RedshiftS3CopyError(bucket) from err
+async def _resolve_aws_s3_integration(integration_id: IntegrationID, team_id: int) -> IAMRole | AWSCredentials:
+ """Resolve an AWS S3 integration into its role ARN or stored credentials."""
+ integration = await _get_aws_s3_integration(integration_id, team_id=team_id)
+
+ match integration:
+ case AWSS3RoleBasedIntegration():
+ return integration.aws_role_arn
+ case AWSS3Integration():
+ return AWSCredentials(
+ aws_access_key_id=integration.aws_access_key_id,
+ aws_secret_access_key=integration.aws_secret_access_key,
+ )
+ case _:
+ typing.assert_never(integration)
+
+
+async def _assume_role_for_stage_bucket(
+ aws_role_arn: IAMRole, inputs: RedshiftCopyActivityInputs, policy_statements: list[PolicyStatement]
+) -> AWSCredentials:
+ team = await Team.objects.aget(id=inputs.batch_export.team_id)
+ external_id = f"posthog-{team.organization_id}"
+
+ return await get_credentials_using_user_aws_role(
+ aws_role_arn,
+ external_id,
+ session_name=f"PostHog-batch-exports-{inputs.batch_export.batch_export_id}",
+ policy_statements=policy_statements,
+ )
+
+
+async def _get_s3_bucket_aws_credentials(
+ inputs: RedshiftCopyActivityInputs,
+) -> tuple[AWSCredentials, RefreshCoroutine | None]:
+ """Resolve the credentials used to stage files in the user's S3 bucket.
+
+ If the credentials are refreshable (i.e. via role assumption), then
+ additionally return a function that may be used to refresh the crednetials.
+ Otherwise, credentials are long lived and the second returned parameter is
+ None.
+ """
+ credentials = inputs.copy.s3_bucket.credentials
+ if isinstance(credentials, IntegrationID):
+ credentials = await _resolve_aws_s3_integration(credentials, inputs.batch_export.team_id)
+
+ if isinstance(credentials, AWSCredentials):
+ return credentials, None
+
+ bucket_name = inputs.copy.s3_bucket.name
+ key_prefix = get_absolute_key_prefix(
+ inputs.copy.s3_key_prefix,
+ inputs.batch_export.data_interval_start,
+ inputs.batch_export.data_interval_end,
+ inputs.batch_export.batch_export_model,
+ )
+ policy_statements = [
+ PolicyStatement(
+ Effect="Allow",
+ Action=["s3:PutObject", "s3:GetObject", "s3:DeleteObject", "s3:AbortMultipartUpload"],
+ Resource=f"arn:aws:s3:::{bucket_name}{key_prefix}*",
+ ),
+ PolicyStatement(
+ Effect="Allow",
+ Action=["s3:ListBucket"],
+ Resource=f"arn:aws:s3:::{bucket_name}",
+ ),
+ ]
+ refresh_credentials = functools.partial(_assume_role_for_stage_bucket, credentials, inputs, policy_statements)
+
+ return await refresh_credentials(), refresh_credentials
+
+
+async def _resolve_copy_authorization(
+ inputs: RedshiftCopyActivityInputs,
+) -> tuple[IAMRole | AWSCredentials, RefreshCoroutine | None]:
+ """Resolve the authorization Redshift uses to read staged files during COPY.
+
+ An integration id resolves to temporary AWS credentials scoped to reading the
+ staged files: a customer role ARN from an integration cannot be passed as
+ `IAM_ROLE` in the COPY statement, since it is not attached to the cluster.
+ """
+ authorization = inputs.copy.authorization
+ if not isinstance(authorization, IntegrationID):
+ return authorization, None
+
+ resolved = await _resolve_aws_s3_integration(authorization, inputs.batch_export.team_id)
+ if isinstance(resolved, AWSCredentials):
+ return resolved, None
+
+ bucket_name = inputs.copy.s3_bucket.name
+ key_prefix = get_absolute_key_prefix(
+ inputs.copy.s3_key_prefix,
+ inputs.batch_export.data_interval_start,
+ inputs.batch_export.data_interval_end,
+ inputs.batch_export.batch_export_model,
+ )
+ policy_statements = [
+ PolicyStatement(
+ Effect="Allow",
+ Action=["s3:GetObject"],
+ Resource=f"arn:aws:s3:::{bucket_name}{key_prefix}*",
+ ),
+ PolicyStatement(
+ Effect="Allow",
+ Action=["s3:ListBucket", "s3:GetBucketLocation"],
+ Resource=f"arn:aws:s3:::{bucket_name}",
+ ),
+ ]
+
+ refresh_credentials = functools.partial(_assume_role_for_stage_bucket, resolved, inputs, policy_statements)
+ credentials = await refresh_credentials()
+ return credentials, refresh_credentials
+
+
@activity.defn
@handle_non_retryable_errors(NON_RETRYABLE_ERROR_TYPES)
async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInputs) -> BatchExportResult:
@@ -1282,6 +1777,7 @@ async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInp
bind_contextvars(
team_id=inputs.batch_export.team_id,
destination="Redshift",
+ integration_id=inputs.integration_id,
data_interval_start=inputs.batch_export.data_interval_start,
data_interval_end=inputs.batch_export.data_interval_end,
database=inputs.connection.database,
@@ -1338,39 +1834,6 @@ async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInp
# TODO: Maybe derive this from user's input?
max_file_size_mb = 100
- if isinstance(inputs.copy.s3_bucket.credentials, IAMRole):
- team = await Team.objects.aget(id=inputs.batch_export.team_id)
- organization_id = str(team.organization_id)
-
- bucket_name = inputs.copy.s3_bucket.name
- key_prefix = get_absolute_key_prefix(
- inputs.copy.s3_key_prefix,
- inputs.batch_export.data_interval_start,
- inputs.batch_export.data_interval_end,
- inputs.batch_export.batch_export_model,
- )
- policy_statements = [
- PolicyStatement(
- Effect="Allow",
- Action=["s3:PutObject", "s3:GetObject", "s3:DeleteObject", "s3:AbortMultipartUpload"],
- Resource=f"arn:aws:s3:::{bucket_name}{key_prefix}*",
- ),
- PolicyStatement(
- Effect="Allow",
- Action=["s3:ListBucket"],
- Resource=f"arn:aws:s3:::{bucket_name}",
- ),
- ]
-
- credentials = await get_credentials_using_user_aws_role(
- inputs.copy.s3_bucket.credentials,
- organization_id,
- session_name=f"PostHog-batch-exports-{inputs.batch_export.batch_export_id}",
- policy_statements=policy_statements,
- )
- else:
- credentials = inputs.copy.s3_bucket.credentials
-
table_schemas = _get_table_schemas(
model=model,
record_batch_schema=record_batch_schema,
@@ -1400,9 +1863,10 @@ async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInp
# table, and the COPY column list names every column in the files. Pre-set
# the transformer's schema to drop columns missing from an existing table,
# as COPY would otherwise fail on them.
+ client_inputs = await _get_redshift_client_inputs(inputs)
try:
async with RedshiftClient.from_inputs(
- inputs.connection, database=inputs.connection.database
+ client_inputs, database=inputs.connection.database
).connect() as redshift_client:
existing_columns = set(
await redshift_client.aget_table_columns(inputs.table.schema_name, inputs.table.name)
@@ -1417,9 +1881,12 @@ async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInp
pa.schema(filtered_fields), json_columns=table_schemas.super_columns
)
+ credentials, refresh_credentials = await _get_s3_bucket_aws_credentials(inputs)
+
async with s3_client(
credentials,
region=inputs.copy.s3_bucket.region_name,
+ refresh_using=refresh_credentials,
) as client:
consumer = ConcurrentS3Consumer(
bucket=inputs.copy.s3_bucket.name,
@@ -1450,8 +1917,9 @@ async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInp
if result.error is not None:
return result
+ client_inputs = await _get_redshift_client_inputs(inputs)
async with RedshiftClient.from_inputs(
- inputs.connection, database=inputs.connection.database
+ client_inputs, database=inputs.connection.database
).connect() as redshift_client:
remove_duplicates = True
@@ -1507,8 +1975,13 @@ async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInp
credentials=credentials,
files_uploaded=consumer.files_uploaded,
manifest_key=manifest_key,
+ refresh_using=refresh_credentials,
)
+ # Resolved after uploads finish: temporary credentials from an assumed
+ # role last one hour, which a long upload could outlive.
+ copy_authorization, refresh_copy_authorization = await _resolve_copy_authorization(inputs)
+
try:
external_logger.info(f"Copying {len(consumer.files_uploaded)} file/s into Redshift")
@@ -1519,16 +1992,17 @@ async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInp
schema_name=inputs.table.schema_name,
s3_bucket=inputs.copy.s3_bucket.name,
manifest_key=manifest_key,
- authorization=inputs.copy.authorization,
+ authorization=copy_authorization,
)
except psycopg.errors.InternalError_ as err:
await check_and_raise_redshift_copy_error(
err,
- authorization=inputs.copy.authorization,
+ authorization=copy_authorization,
bucket=inputs.copy.s3_bucket.name,
region_name=inputs.copy.s3_bucket.region_name,
manifest_key=manifest_key,
files_uploaded=consumer.files_uploaded,
+ refresh_using=refresh_copy_authorization,
)
raise
@@ -1556,6 +2030,7 @@ async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInp
credentials=credentials,
files_uploaded=consumer.files_uploaded,
manifest_key=manifest_key,
+ refresh_using=refresh_credentials,
)
return result
@@ -1625,13 +2100,24 @@ class RedshiftBatchExportWorkflow(PostHogWorkflow):
batch_export_id=inputs.batch_export_id,
destination_default_fields=redshift_default_fields(),
)
- connection_parameters = ConnectionParameters(
- user=inputs.user,
- password=inputs.password,
- host=inputs.host,
- port=inputs.port,
- database=inputs.database,
- )
+ connection_parameters: ConnectionParameters | ServerConnectionParameters
+ if inputs.user is not None and inputs.password is not None and inputs.host is not None:
+ connection_parameters = ConnectionParameters(
+ user=inputs.user,
+ password=inputs.password,
+ host=inputs.host,
+ port=inputs.port,
+ database=inputs.database,
+ )
+ else:
+ # Credentials live in the linked integration. The activity raises a clear,
+ # non-retryable error if there is no integration either; raising here would
+ # retry the workflow task forever.
+ connection_parameters = ServerConnectionParameters(
+ database=inputs.database,
+ port=inputs.port,
+ host=inputs.host,
+ )
table_parameters = TableParameters(
schema_name=inputs.schema,
name=inputs.table_name,
@@ -1654,6 +2140,7 @@ class RedshiftBatchExportWorkflow(PostHogWorkflow):
s3_key_prefix=inputs.copy_inputs.s3_key_prefix,
authorization=inputs.copy_inputs.authorization,
),
+ integration_id=inputs.integration_id,
),
interval=inputs.interval,
maximum_retry_interval_seconds=240,
@@ -1665,6 +2152,7 @@ class RedshiftBatchExportWorkflow(PostHogWorkflow):
batch_export=batch_export_inputs,
connection=connection_parameters,
table=table_parameters,
+ integration_id=inputs.integration_id,
),
interval=inputs.interval,
# TODO: Temporarily bump start to close timeout until we speed up
diff --git a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py b/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
index d41dd23361cd..12092dc13f94 100644
--- a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
@@ -375,7 +375,7 @@ class S3BatchExportResult(BatchExportResult):
class PolicyStatement(typing.TypedDict):
Effect: typing.Literal["Allow", "Deny"]
Action: list[str]
- Resource: str
+ Resource: list[str] | str
async def get_credentials_using_user_aws_role(
diff --git a/products/batch_exports/backend/tests/temporal/destinations/redshift/test_redshift_utils.py b/products/batch_exports/backend/tests/temporal/destinations/redshift/test_redshift_utils.py
index 1619141c441e..e97d4e697d9a 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/redshift/test_redshift_utils.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/redshift/test_redshift_utils.py
@@ -12,11 +12,17 @@ import aioboto3
import pytest_asyncio
import botocore.exceptions
+from posthog.models.integration import AWSRedshiftRoleBasedIntegration, Integration, IntegrationError
+
from products.batch_exports.backend.service import AWSCredentials
from products.batch_exports.backend.temporal.destinations.redshift_batch_export import (
ClientErrorGroup,
InsufficientS3PermissionsError,
+ ProvisionedCluster,
RedshiftS3CopyError,
+ ServerlessWorkgroup,
+ _get_redshift_credentials_policy_statements,
+ _parse_redshift_host,
check_and_raise_redshift_copy_error,
is_s3_read_access_denied,
upload_manifest_file,
@@ -289,3 +295,99 @@ async def test_check_and_raise_redshift_copy_error_iam_role(error, should_raise)
await call
else:
await call # should not raise
+
+
+ "host,expected",
+ [
+ (
+ "examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com",
+ ProvisionedCluster(cluster_identifier="examplecluster", region="us-west-2"),
+ ),
+ (
+ "default-wg.123456789012.us-east-1.redshift-serverless.amazonaws.com",
+ ServerlessWorkgroup(workgroup="default-wg", account_id="123456789012", region="us-east-1"),
+ ),
+ ],
+)
+def test_parse_redshift_host(host, expected):
+ assert _parse_redshift_host(host) == expected
+
+
[email protected]("host", ["localhost", "my-redshift.example.com", "8.8.8.8", ""])
+def test_parse_redshift_host_rejects_unrecognized_endpoints(host):
+ with pytest.raises(IntegrationError):
+ _parse_redshift_host(host)
+
+
+def _aws_redshift_role_integration(**extra_config) -> AWSRedshiftRoleBasedIntegration:
+ integration = Integration(
+ kind=Integration.IntegrationKind.AWS_REDSHIFT,
+ config={
+ "aws_role_arn": "arn:aws:iam::123456789012:role/posthog-batch-exports",
+ "user": "awsuser",
+ **extra_config,
+ },
+ )
+ return AWSRedshiftRoleBasedIntegration(integration)
+
+
+def test_provisioned_cluster_credentials_policy_scopes_to_exact_resources():
+ integration = _aws_redshift_role_integration(groups=["exporters"], auto_create=True)
+ server = ProvisionedCluster(cluster_identifier="examplecluster", region="us-west-2")
+
+ statements = _get_redshift_credentials_policy_statements(integration, server, "posthog")
+
+ assert statements[0]["Action"] == ["redshift:GetClusterCredentials", "redshift:CreateClusterUser"]
+ assert statements[0]["Resource"] == [
+ "arn:aws:redshift:us-west-2:123456789012:dbuser:examplecluster/awsuser",
+ "arn:aws:redshift:us-west-2:123456789012:dbname:examplecluster/posthog",
+ ]
+ assert statements[1]["Action"] == ["redshift:JoinGroup"]
+ assert statements[1]["Resource"] == [
+ "arn:aws:redshift:us-west-2:123456789012:dbgroup:examplecluster/exporters",
+ ]
+ assert all("*" not in resource for statement in statements for resource in statement["Resource"])
+
+
+def test_serverless_workgroup_credentials_policy_scopes_to_workgroup_arn():
+ workgroup_arn = "arn:aws:redshift-serverless:us-east-1:123456789012:workgroup/abc-123"
+ integration = _aws_redshift_role_integration(workgroup_arn=workgroup_arn)
+ server = ServerlessWorkgroup(workgroup="default-wg", account_id="123456789012", region="us-east-1")
+
+ statements = _get_redshift_credentials_policy_statements(integration, server, "posthog")
+
+ assert statements == [
+ {
+ "Effect": "Allow",
+ "Action": ["redshift-serverless:GetCredentials"],
+ "Resource": [workgroup_arn],
+ }
+ ]
+
+
+def test_serverless_workgroup_credentials_policy_requires_workgroup_arn():
+ # There must never be a wildcard fallback here: without the exact workgroup ARN
+ # the policy cannot be scoped, so credentials must not be requested at all.
+ integration = _aws_redshift_role_integration()
+ server = ServerlessWorkgroup(workgroup="default-wg", account_id="123456789012", region="us-east-1")
+
+ with pytest.raises(IntegrationError):
+ _get_redshift_credentials_policy_statements(integration, server, "posthog")
+
+
+ "workgroup_arn",
+ [
+ # Region mismatch.
+ "arn:aws:redshift-serverless:us-west-2:123456789012:workgroup/abc-123",
+ # Account mismatch.
+ "arn:aws:redshift-serverless:us-east-1:999999999999:workgroup/abc-123",
+ ],
+)
+def test_serverless_workgroup_credentials_policy_rejects_mismatched_arn(workgroup_arn):
+ integration = _aws_redshift_role_integration(workgroup_arn=workgroup_arn)
+ server = ServerlessWorkgroup(workgroup="default-wg", account_id="123456789012", region="us-east-1")
+
+ with pytest.raises(IntegrationError):
+ _get_redshift_credentials_policy_statements(integration, server, "posthog")
diff --git a/products/batch_exports/backend/tests/test_service.py b/products/batch_exports/backend/tests/test_service.py
index c29fffc24053..ed8c76f96a05 100644
--- a/products/batch_exports/backend/tests/test_service.py
+++ b/products/batch_exports/backend/tests/test_service.py
@@ -10,11 +10,13 @@ from products.batch_exports.backend.models.batch_export import (
BatchExportRun,
)
from products.batch_exports.backend.service import (
+ AWSCredentials,
AzureBlobBatchExportInputs,
BigQueryBatchExportInputs,
DatabricksBatchExportInputs,
PostgresBatchExportInputs,
RedshiftBatchExportInputs,
+ RedshiftCopyInputs,
S3BatchExportInputs,
aget_or_create_batch_export_backfill,
align_timestamp_to_interval,
@@ -282,3 +284,41 @@ async def test_creates_backfill_without_id_does_not_deduplicate(ateam, batch_exp
def test_align_timestamp_to_interval(timestamp, interval, interval_offset, timezone, expected):
batch_export = BatchExport(interval=interval, interval_offset=interval_offset, timezone=timezone)
assert align_timestamp_to_interval(timestamp, batch_export) == expected
+
+
+class TestRedshiftCopyInputsCredentials:
+ # EncryptedJSONField stringifies scalar leaves on the decrypt round trip, so an
+ # integration id saved as an int can read back as a numeric string.
+ @pytest.mark.parametrize(
+ "authorization,bucket_credentials,expected_authorization,expected_bucket_credentials",
+ [
+ (123, 456, 123, 456),
+ ("123", "456", 123, 456),
+ (
+ "arn:aws:iam::123456789012:role/my-role",
+ {"aws_access_key_id": "key", "aws_secret_access_key": "secret"},
+ "arn:aws:iam::123456789012:role/my-role",
+ AWSCredentials(aws_access_key_id="key", aws_secret_access_key="secret"),
+ ),
+ ],
+ )
+ def test_copy_credentials_are_parsed(
+ self, authorization, bucket_credentials, expected_authorization, expected_bucket_credentials
+ ):
+ inputs = RedshiftBatchExportInputs(
+ batch_export_id="test",
+ team_id=1,
+ database="db",
+ mode="COPY",
+ copy_inputs={ # type: ignore
+ "s3_bucket": "bucket",
+ "region_name": "us-east-1",
+ "s3_key_prefix": "prefix/",
+ "authorization": authorization,
+ "bucket_credentials": bucket_credentials,
+ },
+ )
+
+ assert isinstance(inputs.copy_inputs, RedshiftCopyInputs)
+ assert inputs.copy_inputs.authorization == expected_authorization
+ assert inputs.copy_inputs.bucket_credentials == expected_bucket_credentials