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(s3): Refreshable credentials for S3 clients (#87148)

Tomás Farías Santanaf6f7aac82eab
diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.py
index 096875d34d43..ae78fbb52d8e 100644
--- a/products/batch_exports/backend/service.py
+++ b/products/batch_exports/backend/service.py
@@ -407,6 +407,14 @@ class AWSCredentials:
aws_access_key_id: str
aws_secret_access_key: str = field(repr=False)
aws_session_token: str | None = field(default=None, repr=False)
+ expiration: dt.datetime | None = field(default=None)
+
+ @property
+ def expiry_time(self) -> str | None:
+ """ISO-8601 expiration time for temporary credentials, if available."""
+ if self.expiration is None:
+ return None
+ return self.expiration.isoformat()
@dataclass
diff --git a/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py b/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py
index b82bfc985ec0..341b8f8947e4 100644
--- a/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py
@@ -1,9 +1,9 @@
import re
import json
import uuid
-import typing
import asyncio
import datetime as dt
+import functools
import dataclasses
from django.conf import settings
@@ -18,7 +18,11 @@ from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.logger import get_logger, get_write_only_logger
from products.batch_exports.backend.models.batch_export import BatchExportFileDownload
-from products.batch_exports.backend.service import BatchExportInsertInputs, FileDownloadBatchExportInputs
+from products.batch_exports.backend.service import (
+ AWSCredentials,
+ BatchExportInsertInputs,
+ FileDownloadBatchExportInputs,
+)
from products.batch_exports.backend.temporal.batch_exports import (
DataInterval,
StartBatchExportRunInputs,
@@ -47,15 +51,9 @@ NON_RETRYABLE_ERROR_TYPES = ()
SESSION = aioboto3.Session()
-class Credentials(typing.NamedTuple):
- aws_access_key_id: str
- aws_secret_access_key: str
- aws_session_token: str
-
-
async def _get_temporary_credentials_for_multipart_upload(
bucket: str, prefix: str, /, role_arn: str, duration: int = 3600
-) -> Credentials:
+) -> AWSCredentials:
"""Get temporary AWS credentials for a multipart upload to keys under prefix."""
creds = await _get_temporary_credentials_for_bucket_prefix(
bucket,
@@ -70,7 +68,7 @@ async def _get_temporary_credentials_for_multipart_upload(
async def _get_temporary_credentials_to_head_object(
bucket: str, prefix: str, /, role_arn: str, duration: int = 900
-) -> Credentials:
+) -> AWSCredentials:
"""Get temporary AWS credentials for HEAD object requests for keys under prefix."""
creds = await _get_temporary_credentials_for_bucket_prefix(
bucket,
@@ -93,7 +91,7 @@ async def _get_temporary_credentials_for_bucket_prefix(
duration: int = 3600,
max_attempts: int = 5,
delay: int | float = 1.0,
-) -> Credentials:
+) -> AWSCredentials:
"""Get temporary credentials scoped to operate only on the bucket's prefix.
The credentials should be limited to a set of actions using the `actions` argument.
@@ -127,11 +125,14 @@ async def _get_temporary_credentials_for_bucket_prefix(
raise
await asyncio.sleep(delay * (2**attempt))
-
- return Credentials(
- response["Credentials"]["AccessKeyId"],
- response["Credentials"]["SecretAccessKey"],
- response["Credentials"]["SessionToken"],
+ else:
+ break
+
+ return AWSCredentials(
+ aws_access_key_id=response["Credentials"]["AccessKeyId"],
+ aws_secret_access_key=response["Credentials"]["SecretAccessKey"],
+ aws_session_token=response["Credentials"]["SessionToken"],
+ expiration=response["Credentials"]["Expiration"],
)
@@ -244,7 +245,8 @@ async def export_to_file_download_bucket_with_temporary_credentials(inputs: Expo
batch_export_id=inputs.batch_export.batch_export_id, batch_export_run_id=inputs.batch_export.run_id
)
- credentials = await _get_temporary_credentials_for_multipart_upload(
+ refresh_credentials = functools.partial(
+ _get_temporary_credentials_for_multipart_upload,
inputs.s3_bucket.name,
f"batch-exports/{inputs.batch_export.batch_export_id}/{inputs.batch_export.run_id}",
role_arn=inputs.aws_role_arn,
@@ -257,9 +259,6 @@ async def export_to_file_download_bucket_with_temporary_credentials(inputs: Expo
compression=inputs.compression,
file_format=inputs.file_format,
max_file_size_mb=inputs.max_file_size_mb,
- aws_access_key_id=credentials.aws_access_key_id,
- aws_secret_access_key=credentials.aws_secret_access_key,
- aws_session_token=credentials.aws_session_token,
data_interval_start=inputs.batch_export.data_interval_start,
data_interval_end=inputs.batch_export.data_interval_end,
exclude_events=inputs.batch_export.exclude_events,
@@ -270,6 +269,7 @@ async def export_to_file_download_bucket_with_temporary_credentials(inputs: Expo
batch_export_model=inputs.batch_export.batch_export_model,
batch_export_id=inputs.batch_export.batch_export_id,
destination_default_fields=inputs.batch_export.destination_default_fields,
+ refresh_credentials=refresh_credentials,
)
result = await insert_into_s3_activity_from_stage(s3_insert_inputs)
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 c5d83db53141..01ca44b76917 100644
--- a/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py
@@ -1066,9 +1066,7 @@ async def upload_manifest_file(
"""
async with s3_client(
- credentials.aws_access_key_id,
- credentials.aws_secret_access_key,
- credentials.aws_session_token,
+ credentials,
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,
@@ -1154,9 +1152,7 @@ async def delete_uploaded_files(
this fails.
"""
async with s3_client(
- credentials.aws_access_key_id,
- credentials.aws_secret_access_key,
- credentials.aws_session_token,
+ credentials,
region=region_name,
) as client:
@@ -1190,9 +1186,7 @@ async def is_s3_read_access_denied(
"""
try:
async with s3_client(
- credentials.aws_access_key_id,
- credentials.aws_secret_access_key,
- credentials.aws_session_token,
+ credentials,
region=region_name,
) as client:
for key in keys:
@@ -1424,9 +1418,7 @@ async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInp
)
async with s3_client(
- credentials.aws_access_key_id,
- credentials.aws_secret_access_key,
- credentials.aws_session_token,
+ credentials,
region=inputs.copy.s3_bucket.region_name,
) as client:
consumer = ConcurrentS3Consumer(
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 ba60d546234e..d41dd23361cd 100644
--- a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
@@ -3,6 +3,7 @@ import typing
import asyncio
import secrets
import datetime as dt
+import functools
import contextlib
import dataclasses
import collections.abc
@@ -11,6 +12,8 @@ import pyarrow as pa
import aioboto3
import botocore.exceptions
from aiobotocore.config import AioConfig
+from aiobotocore.credentials import AioRefreshableCredentials
+from aiobotocore.session import get_session
from opentelemetry import trace
if typing.TYPE_CHECKING:
@@ -114,6 +117,8 @@ EXTERNAL_LOGGER = get_logger("EXTERNAL")
TRACER = trace.get_tracer(__name__)
SESSION = aioboto3.Session()
+RefreshCoroutine = typing.Callable[[], typing.Awaitable[AWSCredentials]]
+
class UnsupportedFileFormatError(Exception):
"""Raised when an unsupported file format is requested."""
@@ -190,6 +195,8 @@ class S3InsertInputs(BatchExportInsertInputs):
file_format: str = "JSONLines"
max_file_size_mb: int | None = None
use_virtual_style_addressing: bool = False
+ # Only usable when calling the activity as a function, Temporal cannot serialize this.
+ refresh_credentials: RefreshCoroutine | None = None
def get_s3_key_from_inputs(inputs: S3InsertInputs, file_number: int = 0) -> str:
@@ -488,23 +495,66 @@ async def get_credentials_using_user_aws_role(
aws_access_key_id=second_response["Credentials"]["AccessKeyId"],
aws_secret_access_key=second_response["Credentials"]["SecretAccessKey"],
aws_session_token=second_response["Credentials"]["SessionToken"],
+ expiration=second_response["Credentials"]["Expiration"],
+ )
+
+
+def make_refresh_credentials_as_metadata(
+ refresh_using: RefreshCoroutine,
+) -> typing.Callable[[], typing.Awaitable[dict[str, str]]]:
+ async def _refresh():
+ creds = await refresh_using()
+
+ assert creds.aws_session_token
+ assert creds.expiry_time
+
+ return {
+ "access_key": creds.aws_access_key_id,
+ "secret_key": creds.aws_secret_access_key,
+ "token": creds.aws_session_token,
+ "expiry_time": creds.expiry_time,
+ }
+
+ return _refresh
+
+
+def get_refreshable_session(credentials: AWSCredentials, refresh_using: RefreshCoroutine) -> aioboto3.Session:
+ wrapped = make_refresh_credentials_as_metadata(refresh_using)
+
+ assert credentials.aws_session_token
+ assert credentials.expiration
+
+ refreshable_credentials = AioRefreshableCredentials(
+ access_key=credentials.aws_access_key_id,
+ secret_key=credentials.aws_secret_access_key,
+ token=credentials.aws_session_token,
+ expiry_time=credentials.expiration,
+ refresh_using=wrapped,
+ method="sts-assume-role",
)
+ botocore_session = get_session()
+ botocore_session._credentials = refreshable_credentials # type: ignore[attr-defined]
+
+ return aioboto3.Session(botocore_session=botocore_session)
+
@contextlib.asynccontextmanager
async def s3_client(
- aws_access_key_id: str,
- aws_secret_access_key: str,
- aws_session_token: str | None,
+ aws_credentials: AWSCredentials,
region: str,
use_virtual_style_addressing: bool = False,
endpoint_url: str | None = None,
+ refresh_using: RefreshCoroutine | None = None,
) -> collections.abc.AsyncIterator["S3Client"]:
- session = aioboto3.Session(
- aws_access_key_id=aws_access_key_id,
- aws_secret_access_key=aws_secret_access_key,
- aws_session_token=aws_session_token,
- )
+ if refresh_using is not None:
+ session = get_refreshable_session(aws_credentials, refresh_using)
+ else:
+ 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,
+ )
config: dict[str, typing.Any] = {
# Increase connection pool, so to ensure we're not limited by this
@@ -560,17 +610,17 @@ async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> S3BatchE
async with Heartbeater():
# Integration-backed exports resolve credentials at run time; legacy exports carry them inline.
# TODO: require integration
- aws_access_key_id = inputs.aws_access_key_id
- aws_secret_access_key = inputs.aws_secret_access_key
- aws_session_token = inputs.aws_session_token
endpoint_url = inputs.endpoint_url
+ refresh_credentials = inputs.refresh_credentials
if inputs.integration_id is not None:
integration = await _get_s3_integration(inputs.integration_id, inputs.team_id)
if isinstance(integration, AWSS3Integration):
- aws_access_key_id = integration.aws_access_key_id
- aws_secret_access_key = integration.aws_secret_access_key
+ credentials = AWSCredentials(
+ aws_access_key_id=integration.aws_access_key_id,
+ aws_secret_access_key=integration.aws_secret_access_key,
+ )
if isinstance(integration, AWSS3RoleBasedIntegration):
team = await Team.objects.aget(id=inputs.team_id)
@@ -619,27 +669,33 @@ async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> S3BatchE
)
)
- credentials = await get_credentials_using_user_aws_role(
+ refresh_credentials = functools.partial(
+ get_credentials_using_user_aws_role,
integration.aws_role_arn,
external_id,
session_name=f"PostHog-batch-exports-{inputs.batch_export_id}",
policy_statements=policy_statements,
)
- 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,
- )
+ credentials = await refresh_credentials()
if isinstance(integration, S3CompatibleIntegration):
- aws_access_key_id = integration.aws_access_key_id
- aws_secret_access_key = integration.aws_secret_access_key
+ credentials = AWSCredentials(
+ aws_access_key_id=integration.aws_access_key_id,
+ aws_secret_access_key=integration.aws_secret_access_key,
+ )
endpoint_url = integration.endpoint_url
- if not aws_access_key_id or not aws_secret_access_key:
- # At these point these need to be defined: either by us assuming a new
- # role, by an integration, or by the inputs.
- raise InvalidCredentialsError("AWS access key ID and secret access key cannot be empty")
+ else:
+ if refresh_credentials is not None:
+ credentials = await refresh_credentials()
+ else:
+ if not inputs.aws_access_key_id or not inputs.aws_secret_access_key:
+ raise InvalidCredentialsError("AWS access key ID and secret access key cannot be empty")
+ credentials = AWSCredentials(
+ aws_access_key_id=inputs.aws_access_key_id,
+ aws_secret_access_key=inputs.aws_secret_access_key,
+ aws_session_token=inputs.aws_session_token,
+ )
external_logger = EXTERNAL_LOGGER.bind()
external_logger.info(
@@ -695,12 +751,11 @@ async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> S3BatchE
)
async with s3_client(
- aws_access_key_id,
- aws_secret_access_key,
- aws_session_token,
+ credentials,
use_virtual_style_addressing=inputs.use_virtual_style_addressing,
region=inputs.region,
endpoint_url=endpoint_url,
+ refresh_using=refresh_credentials,
) as client:
consumer = ConcurrentS3Consumer.from_inputs(
s3_client=client,
diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/test_refreshable_credentials.py b/products/batch_exports/backend/tests/temporal/destinations/s3/test_refreshable_credentials.py
new file mode 100644
index 000000000000..3c19c289fdfe
--- /dev/null
+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/test_refreshable_credentials.py
@@ -0,0 +1,77 @@
+import typing
+import datetime as dt
+import collections.abc
+
+import pytest
+
+import aioboto3
+from aiobotocore.credentials import AioRefreshableCredentials
+from botocore.credentials import ReadOnlyCredentials
+
+from products.batch_exports.backend.service import AWSCredentials
+from products.batch_exports.backend.temporal.destinations.s3_batch_export import (
+ RefreshCoroutine,
+ get_refreshable_session,
+)
+
+pytestmark = [pytest.mark.asyncio]
+
+
+def make_refresh_stub(refreshed: AWSCredentials) -> tuple[list[int], RefreshCoroutine]:
+ calls: list[int] = []
+
+ async def refresh() -> AWSCredentials:
+ calls.append(1)
+ return refreshed
+
+ return calls, refresh
+
+
+async def get_frozen_session_credentials(session: aioboto3.Session) -> ReadOnlyCredentials:
+ # aioboto3 sessions return a coroutine at runtime, but the stubs carry boto3's sync signature.
+ credentials = await typing.cast(collections.abc.Awaitable[AioRefreshableCredentials], session.get_credentials())
+ return await credentials.get_frozen_credentials()
+
+
+async def test_get_refreshable_session_refreshes_expired_credentials():
+ now = dt.datetime.now(dt.UTC)
+ initial = AWSCredentials(
+ aws_access_key_id="initial-key",
+ aws_secret_access_key="initial-secret",
+ aws_session_token="initial-token",
+ expiration=now - dt.timedelta(minutes=5),
+ )
+ refreshed = AWSCredentials(
+ aws_access_key_id="refreshed-key",
+ aws_secret_access_key="refreshed-secret",
+ aws_session_token="refreshed-token",
+ expiration=now + dt.timedelta(hours=1),
+ )
+ calls, refresh = make_refresh_stub(refreshed)
+
+ session = get_refreshable_session(initial, refresh)
+ frozen = await get_frozen_session_credentials(session)
+
+ assert len(calls) == 1
+ assert frozen.access_key == "refreshed-key"
+ assert frozen.secret_key == "refreshed-secret"
+ assert frozen.token == "refreshed-token"
+
+
+async def test_get_refreshable_session_does_not_refresh_valid_credentials():
+ now = dt.datetime.now(dt.UTC)
+ initial = AWSCredentials(
+ aws_access_key_id="initial-key",
+ aws_secret_access_key="initial-secret",
+ aws_session_token="initial-token",
+ expiration=now + dt.timedelta(hours=1),
+ )
+ calls, refresh = make_refresh_stub(initial)
+
+ session = get_refreshable_session(initial, refresh)
+ frozen = await get_frozen_session_credentials(session)
+
+ assert len(calls) == 0
+ assert frozen.access_key == "initial-key"
+ assert frozen.secret_key == "initial-secret"
+ assert frozen.token == "initial-token"