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-modal): Add support for role based assumption (#70484)

Tomás Farías Santanac643db7e06ce
diff --git a/frontend/src/scenes/integrations/aws-s3/AwsS3SetupModal.test.tsx b/frontend/src/scenes/integrations/aws-s3/AwsS3SetupModal.test.tsx
new file mode 100644
index 000000000000..1a8dbe9af53e
--- /dev/null
+++ b/frontend/src/scenes/integrations/aws-s3/AwsS3SetupModal.test.tsx
@@ -0,0 +1,76 @@
+import { MOCK_ORGANIZATION_ID } from 'lib/api.mock'
+
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { Provider } from 'kea'
+
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+
+import { initKeaTests } from '~/test/init'
+import { PreflightStatus, Region } from '~/types'
+
+import { AwsS3SetupModal } from './AwsS3SetupModal'
+
+describe('AwsS3SetupModal', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ const setRegion = (region: Region | null): void => {
+ preflightLogic.mount()
+ preflightLogic.actions.loadPreflightSuccess({ region } as PreflightStatus)
+ }
+
+ it('opens on the role tab with the trust policy requirements, including the external ID', async () => {
+ render(
+ <Provider>
+ <AwsS3SetupModal isOpen onComplete={jest.fn()} />
+ </Provider>
+ )
+
+ expect(screen.getByText('IAM role ARN')).toBeInTheDocument()
+ expect(screen.getByText('Requirements')).toBeInTheDocument()
+ expect(screen.queryByText('AWS Access Key ID')).not.toBeInTheDocument()
+ // The external ID users must set in their trust policy is posthog-{organization ID}
+ await waitFor(() => {
+ expect(screen.getByText(`posthog-${MOCK_ORGANIZATION_ID}`)).toBeInTheDocument()
+ })
+ })
+
+ it.each<[string, Region | null, string]>([
+ ['US cloud', Region.US, 'arn:aws:iam::309986977637:role/posthog-external-batch-exports'],
+ ['EU cloud', Region.EU, 'arn:aws:iam::623789312881:role/posthog-external-batch-exports'],
+ ['dev', Region.DEV, 'Check with your instance administrator'],
+ ['self-hosted', null, 'Check with your instance administrator'],
+ ])('shows the right role to trust on %s', (_label, region, expectedText) => {
+ setRegion(region)
+ render(
+ <Provider>
+ <AwsS3SetupModal isOpen onComplete={jest.fn()} />
+ </Provider>
+ )
+
+ expect(screen.getByText(expectedText, { exact: false })).toBeInTheDocument()
+ })
+
+ it('shows credential fields and the long-lived credentials warning on the access keys tab', async () => {
+ render(
+ <Provider>
+ <AwsS3SetupModal isOpen onComplete={jest.fn()} />
+ </Provider>
+ )
+
+ await userEvent.click(screen.getByText('Access keys'))
+
+ expect(screen.getByText('AWS Access Key ID')).toBeInTheDocument()
+ expect(screen.getByText('AWS Secret Access Key')).toBeInTheDocument()
+ expect(screen.getByText(/long-lived credentials/)).toBeInTheDocument()
+ expect(screen.queryByText('IAM role ARN')).not.toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/scenes/integrations/aws-s3/AwsS3SetupModal.tsx b/frontend/src/scenes/integrations/aws-s3/AwsS3SetupModal.tsx
index dd8f843b970c..95aed9fbf795 100644
--- a/frontend/src/scenes/integrations/aws-s3/AwsS3SetupModal.tsx
+++ b/frontend/src/scenes/integrations/aws-s3/AwsS3SetupModal.tsx
@@ -1,21 +1,35 @@
import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
-import { LemonButton, LemonInput, LemonModal } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonInput, LemonModal, LemonTabs } from '@posthog/lemon-ui'
import { LemonField } from 'lib/lemon-ui/LemonField'
+import { organizationLogic } from 'scenes/organizationLogic'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+
+import { Region } from '~/types'
import { AwsS3SetupModalLogicProps, awsS3SetupModalLogic } from './awsS3SetupModalLogic'
+const POSTHOG_ROLE_ARN_BY_REGION: Partial<Record<Region, string>> = {
+ [Region.US]: 'arn:aws:iam::309986977637:role/posthog-external-batch-exports',
+ [Region.EU]: 'arn:aws:iam::623789312881:role/posthog-external-batch-exports',
+}
+
export const AwsS3SetupModal = (props: AwsS3SetupModalLogicProps): JSX.Element => {
- const { isAwsS3IntegrationSubmitting } = useValues(awsS3SetupModalLogic(props))
- const { submitAwsS3Integration } = useActions(awsS3SetupModalLogic(props))
+ const logic = awsS3SetupModalLogic(props)
+ const { currentOrganization } = useValues(organizationLogic)
+ const { preflight } = useValues(preflightLogic)
+ const { authMode, isAwsS3IntegrationSubmitting } = useValues(logic)
+ const { setAuthMode, submitAwsS3Integration } = useActions(logic)
+
+ const posthogRoleArn = preflight?.region ? POSTHOG_ROLE_ARN_BY_REGION[preflight.region] : undefined
return (
<LemonModal
isOpen={props.isOpen}
title="Configure AWS S3 connection"
- description="Enter your AWS credentials to connect PostHog to your S3 buckets. They are stored encrypted and can be reused across exports."
+ description="Connect PostHog to your S3 buckets. Connections can be reused across exports."
onClose={props.onComplete}
footer={
<>
@@ -32,12 +46,88 @@ export const AwsS3SetupModal = (props: AwsS3SetupModalLogicProps): JSX.Element =
<LemonField name="name" label="Name" info="A name to identify this connection across exports.">
<LemonInput placeholder="e.g. Production data lake" />
</LemonField>
- <LemonField name="awsAccessKeyId" label="AWS Access Key ID">
- <LemonInput placeholder="e.g. AKIAIOSFODNN7EXAMPLE" autoComplete="off" />
- </LemonField>
- <LemonField name="awsSecretAccessKey" label="AWS Secret Access Key">
- <LemonInput type="password" placeholder="e.g. secret-key" autoComplete="new-password" />
- </LemonField>
+ <LemonTabs
+ activeKey={authMode}
+ onChange={setAuthMode}
+ tabs={[
+ {
+ key: 'role',
+ label: 'Assume IAM role',
+ },
+ {
+ key: 'access_key',
+ label: 'Access keys',
+ },
+ ]}
+ />
+ {authMode === 'role' ? (
+ <>
+ <LemonField
+ name="awsRoleArn"
+ label="IAM role ARN"
+ info="The ARN of an IAM role in your AWS account that PostHog will assume to write export data."
+ >
+ <LemonInput
+ placeholder="e.g. arn:aws:iam::123456789012:role/posthog-batch-exports"
+ autoComplete="off"
+ />
+ </LemonField>
+ <div className="border border-border rounded p-4 bg-bg-light flex flex-col gap-3 text-sm">
+ <p className="font-semibold m-0">Requirements</p>
+ <div className="flex gap-3 items-start">
+ <span className="bg-primary-highlight text-primary-alt rounded-full w-5 h-5 flex items-center justify-center text-xs font-semibold shrink-0 mt-0.5">
+ 1
+ </span>
+ <p className="m-0 text-secondary">
+ {posthogRoleArn ? (
+ <>
+ Create an IAM role with a trust policy that allows PostHog's role{' '}
+ <code>{posthogRoleArn}</code> to assume it.
+ </>
+ ) : (
+ <>
+ Create an IAM role with a trust policy that allows PostHog's role to assume
+ it. Check with your instance administrator to obtain the role to trust.
+ </>
+ )}
+ </p>
+ </div>
+ <div className="flex gap-3 items-start">
+ <span className="bg-primary-highlight text-primary-alt rounded-full w-5 h-5 flex items-center justify-center text-xs font-semibold shrink-0 mt-0.5">
+ 2
+ </span>
+ <p className="m-0 text-secondary">
+ The trust policy must require an <code>sts:ExternalId</code> condition equal to{' '}
+ <code>posthog-{currentOrganization?.id}</code>. PostHog verifies this condition is
+ enforced and exports will fail without it.
+ </p>
+ </div>
+ <div className="flex gap-3 items-start">
+ <span className="bg-primary-highlight text-primary-alt rounded-full w-5 h-5 flex items-center justify-center text-xs font-semibold shrink-0 mt-0.5">
+ 3
+ </span>
+ <p className="m-0 text-secondary">
+ Grant the role <code>s3:PutObject</code> and <code>s3:AbortMultipartUpload</code> on
+ the destination bucket and prefix. If the bucket uses KMS encryption, also grant{' '}
+ <code>kms:GenerateDataKey</code> and <code>kms:Decrypt</code> on the key.
+ </p>
+ </div>
+ </div>
+ </>
+ ) : (
+ <>
+ <LemonBanner type="warning">
+ Access keys are long-lived credentials stored by PostHog (encrypted). Prefer letting PostHog
+ assume an IAM role to avoid creating and storing long-lived credentials.
+ </LemonBanner>
+ <LemonField name="awsAccessKeyId" label="AWS Access Key ID">
+ <LemonInput placeholder="e.g. AKIAIOSFODNN7EXAMPLE" autoComplete="off" />
+ </LemonField>
+ <LemonField name="awsSecretAccessKey" label="AWS Secret Access Key">
+ <LemonInput type="password" placeholder="e.g. secret-key" autoComplete="new-password" />
+ </LemonField>
+ </>
+ )}
</Form>
</LemonModal>
)
diff --git a/frontend/src/scenes/integrations/aws-s3/awsS3SetupModalLogic.test.ts b/frontend/src/scenes/integrations/aws-s3/awsS3SetupModalLogic.test.ts
new file mode 100644
index 000000000000..b5d9b14998ce
--- /dev/null
+++ b/frontend/src/scenes/integrations/aws-s3/awsS3SetupModalLogic.test.ts
@@ -0,0 +1,105 @@
+import { expectLogic } from 'kea-test-utils'
+
+import apiReal from 'lib/api'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { awsS3SetupModalLogic } from './awsS3SetupModalLogic'
+
+describe('awsS3SetupModalLogic', () => {
+ let logic: ReturnType<typeof awsS3SetupModalLogic.build>
+ let createSpy: jest.SpyInstance
+
+ useMocks({
+ get: {
+ '/api/environments/:team_id/integrations/': () => [200, { results: [] }],
+ },
+ })
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = awsS3SetupModalLogic({ isOpen: true, onComplete: jest.fn() })
+ logic.mount()
+ createSpy = jest.spyOn(apiReal.integrations, 'create').mockResolvedValue({
+ id: 42,
+ kind: 'aws-s3',
+ display_name: 'my connection',
+ icon_url: '',
+ config: {},
+ created_at: '2026-07-13T00:00:00Z',
+ } as any)
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it('sends only aws_role_arn in role mode', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setAwsS3IntegrationValues({
+ name: 'my connection',
+ awsRoleArn: 'arn:aws:iam::123456789012:role/posthog-batch-exports',
+ })
+ logic.actions.submitAwsS3Integration()
+ }).toFinishAllListeners()
+
+ expect(createSpy).toHaveBeenCalledWith({
+ kind: 'aws-s3',
+ config: {
+ name: 'my connection',
+ aws_role_arn: 'arn:aws:iam::123456789012:role/posthog-batch-exports',
+ },
+ })
+ })
+
+ it('sends only access keys in access key mode', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setAuthMode('access_key')
+ logic.actions.setAwsS3IntegrationValues({
+ name: 'my connection',
+ awsAccessKeyId: 'AKIAIOSFODNN7EXAMPLE',
+ awsSecretAccessKey: 'secret',
+ })
+ logic.actions.submitAwsS3Integration()
+ }).toFinishAllListeners()
+
+ expect(createSpy).toHaveBeenCalledWith({
+ kind: 'aws-s3',
+ config: {
+ name: 'my connection',
+ aws_access_key_id: 'AKIAIOSFODNN7EXAMPLE',
+ aws_secret_access_key: 'secret',
+ },
+ })
+ })
+
+ it.each(['', 'not-an-arn', 'arn:aws:iam::123:role/too-short-account'])(
+ 'does not submit in role mode with invalid ARN %p',
+ async (awsRoleArn) => {
+ await expectLogic(logic, () => {
+ logic.actions.setAwsS3IntegrationValues({ name: 'my connection', awsRoleArn })
+ logic.actions.submitAwsS3Integration()
+ }).toFinishAllListeners()
+
+ expect(createSpy).not.toHaveBeenCalled()
+ }
+ )
+
+ it('clears credential fields when switching auth mode', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setAwsS3IntegrationValues({
+ name: 'my connection',
+ awsRoleArn: 'arn:aws:iam::123456789012:role/posthog-batch-exports',
+ })
+ logic.actions.setAuthMode('access_key')
+ }).toFinishAllListeners()
+
+ expect(logic.values.awsS3Integration).toMatchObject({
+ name: 'my connection',
+ awsRoleArn: '',
+ awsAccessKeyId: '',
+ awsSecretAccessKey: '',
+ })
+ })
+})
diff --git a/frontend/src/scenes/integrations/aws-s3/awsS3SetupModalLogic.ts b/frontend/src/scenes/integrations/aws-s3/awsS3SetupModalLogic.ts
index 1e68bb94395f..a06320f3a5b6 100644
--- a/frontend/src/scenes/integrations/aws-s3/awsS3SetupModalLogic.ts
+++ b/frontend/src/scenes/integrations/aws-s3/awsS3SetupModalLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, connect, kea, path, props } from 'kea'
+import { MakeLogicType, actions, connect, kea, listeners, path, props, reducers } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
@@ -8,6 +8,10 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { IntegrationType } from '~/types'
+export type S3AuthMode = 'role' | 'access_key'
+
+const IAM_ROLE_ARN_REGEX = /^arn:aws:iam::\d{12}:role\/.+$/
+
export interface AwsS3SetupModalLogicProps {
isOpen: boolean
integration?: IntegrationType | null
@@ -16,8 +20,10 @@ export interface AwsS3SetupModalLogicProps {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface awsS3SetupModalLogicValues {
+ authMode: S3AuthMode
awsS3Integration: {
awsAccessKeyId: string
+ awsRoleArn: string
awsSecretAccessKey: string
name: string
}
@@ -26,6 +32,7 @@ export interface awsS3SetupModalLogicValues {
awsS3IntegrationErrors: DeepPartialMap<
{
awsAccessKeyId: string
+ awsRoleArn: string
awsSecretAccessKey: string
name: string
},
@@ -38,6 +45,7 @@ export interface awsS3SetupModalLogicValues {
awsS3IntegrationValidationErrors: DeepPartialMap<
{
awsAccessKeyId: string
+ awsRoleArn: string
awsSecretAccessKey: string
name: string
},
@@ -51,13 +59,22 @@ export interface awsS3SetupModalLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface awsS3SetupModalLogicActions {
loadIntegrations: () => any // integrationsLogic
- resetAwsS3Integration: (values?: { awsAccessKeyId: string; awsSecretAccessKey: string; name: string }) => {
+ resetAwsS3Integration: (values?: {
+ awsAccessKeyId: string
+ awsRoleArn: string
+ awsSecretAccessKey: string
+ name: string
+ }) => {
values?: {
awsAccessKeyId: string
+ awsRoleArn: string
awsSecretAccessKey: string
name: string
}
}
+ setAuthMode: (mode: S3AuthMode) => {
+ mode: S3AuthMode
+ }
setAwsS3IntegrationManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
@@ -71,12 +88,14 @@ export interface awsS3SetupModalLogicActions {
setAwsS3IntegrationValues: (
values: DeepPartial<{
awsAccessKeyId: string
+ awsRoleArn: string
awsSecretAccessKey: string
name: string
}>
) => {
values: DeepPartial<{
awsAccessKeyId: string
+ awsRoleArn: string
awsSecretAccessKey: string
name: string
}>
@@ -93,22 +112,26 @@ export interface awsS3SetupModalLogicActions {
}
submitAwsS3IntegrationRequest: (awsS3Integration: {
awsAccessKeyId: string
+ awsRoleArn: string
awsSecretAccessKey: string
name: string
}) => {
awsS3Integration: {
awsAccessKeyId: string
+ awsRoleArn: string
awsSecretAccessKey: string
name: string
}
}
submitAwsS3IntegrationSuccess: (awsS3Integration: {
awsAccessKeyId: string
+ awsRoleArn: string
awsSecretAccessKey: string
name: string
}) => {
awsS3Integration: {
awsAccessKeyId: string
+ awsRoleArn: string
awsSecretAccessKey: string
name: string
}
@@ -130,27 +153,58 @@ export const awsS3SetupModalLogic = kea<awsS3SetupModalLogicType>([
connect(() => ({
actions: [integrationsLogic, ['loadIntegrations']],
})),
+ actions({
+ setAuthMode: (mode: S3AuthMode) => ({ mode }),
+ }),
+ reducers({
+ authMode: [
+ 'role' as S3AuthMode,
+ {
+ setAuthMode: (_, { mode }) => mode,
+ },
+ ],
+ }),
forms(({ props, actions, values }) => ({
awsS3Integration: {
defaults: {
name: '',
awsAccessKeyId: '',
awsSecretAccessKey: '',
+ awsRoleArn: '',
},
- errors: ({ name, awsAccessKeyId, awsSecretAccessKey }) => ({
+ errors: ({ name, awsAccessKeyId, awsSecretAccessKey, awsRoleArn }) => ({
name: name.trim() ? undefined : 'Name is required',
- awsAccessKeyId: awsAccessKeyId.trim() ? undefined : 'Access Key ID is required',
- awsSecretAccessKey: awsSecretAccessKey.trim() ? undefined : 'Secret Access Key is required',
+ awsAccessKeyId:
+ values.authMode === 'role' || awsAccessKeyId.trim() ? undefined : 'Access Key ID is required',
+ awsSecretAccessKey:
+ values.authMode === 'role' || awsSecretAccessKey.trim()
+ ? undefined
+ : 'Secret Access Key is required',
+ awsRoleArn:
+ values.authMode !== 'role'
+ ? undefined
+ : !awsRoleArn.trim()
+ ? 'IAM role ARN is required'
+ : !IAM_ROLE_ARN_REGEX.test(awsRoleArn.trim())
+ ? 'Enter a valid IAM role ARN, e.g. arn:aws:iam::123456789012:role/my-role'
+ : undefined,
}),
submit: async () => {
try {
+ const { name, awsAccessKeyId, awsSecretAccessKey, awsRoleArn } = values.awsS3Integration
const integration = await api.integrations.create({
kind: 'aws-s3',
- config: {
- name: values.awsS3Integration.name,
- aws_access_key_id: values.awsS3Integration.awsAccessKeyId,
- aws_secret_access_key: values.awsS3Integration.awsSecretAccessKey,
- },
+ config:
+ values.authMode === 'role'
+ ? {
+ name,
+ aws_role_arn: awsRoleArn.trim(),
+ }
+ : {
+ name,
+ aws_access_key_id: awsAccessKeyId,
+ aws_secret_access_key: awsSecretAccessKey,
+ },
})
actions.loadIntegrations()
lemonToast.success('AWS S3 connection created successfully!')
@@ -162,4 +216,13 @@ export const awsS3SetupModalLogic = kea<awsS3SetupModalLogicType>([
},
},
})),
+ listeners(({ actions }) => ({
+ setAuthMode: () => {
+ actions.setAwsS3IntegrationValues({
+ awsAccessKeyId: '',
+ awsSecretAccessKey: '',
+ awsRoleArn: '',
+ })
+ },
+ })),
])
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 bf243fa22ce5..6c649c3524dd 100644
--- a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
@@ -575,7 +575,7 @@ async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> S3BatchE
if isinstance(integration, AwsS3RoleBasedIntegration):
team = await Team.objects.aget(id=inputs.team_id)
- organization_id = str(team.organization_id)
+ external_id = f"posthog-{team.organization_id}"
bucket_name = inputs.bucket_name
key_prefix = get_absolute_key_prefix(
@@ -622,7 +622,7 @@ async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> S3BatchE
credentials = await get_credentials_using_user_aws_role(
integration.aws_role_arn,
- organization_id,
+ external_id,
session_name=f"PostHog-batch-exports-{inputs.batch_export_id}",
policy_statements=policy_statements,
)
diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/conftest.py b/products/batch_exports/backend/tests/temporal/destinations/s3/conftest.py
index 672e8731a656..948c62e19f34 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/s3/conftest.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/conftest.py
@@ -348,7 +348,7 @@ def external_id(request, aorganization) -> str | None:
try:
return request.param
except Exception:
- return str(aorganization.id)
+ return f"posthog-{aorganization.id}"
@pytest_asyncio.fixture
diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/test_activity_with_role_assumption.py b/products/batch_exports/backend/tests/temporal/destinations/s3/test_activity_with_role_assumption.py
index dac7f4aa8cf5..d98f2bce1957 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/s3/test_activity_with_role_assumption.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/test_activity_with_role_assumption.py
@@ -37,7 +37,7 @@ def bucket_name(request) -> str:
async def test_get_credentials_using_user_aws_role(
external_aws_role_arn: str, destination_aws_role_arn: str, aorganization: Organization, bucket_name: str
):
- external_id = str(aorganization.id)
+ external_id = f"posthog-{aorganization.id}"
with override_settings(BATCH_EXPORT_S3_EXTERNAL_ROLE_ARN=external_aws_role_arn):
credentials = await get_credentials_using_user_aws_role(