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.

fix(batch-import): assume migration iam role before customer's role (#69515)

Nick Best0d908fee7715
diff --git a/rust/batch-import-worker/src/config.rs b/rust/batch-import-worker/src/config.rs
index ddda09cf7cc5..a0098b3616a8 100644
--- a/rust/batch-import-worker/src/config.rs
+++ b/rust/batch-import-worker/src/config.rs
@@ -91,6 +91,14 @@ pub struct Config {
#[envconfig(from = "CAPTURE_URL", default = "http://localhost:3307")]
pub capture_url: String,
+ // Dedicated cross-account role for managed-migration S3 imports. Customer trust
+ // policies reference this role's ARN (not the worker's own identity), so the worker
+ // role-chains through it: ambient creds -> managed-migrations role -> customer role.
+ // Required for IAM-role-auth jobs; when unset they fail with a contact-support error
+ // (the customer hop can never succeed without it). Key-auth jobs don't need it.
+ #[envconfig(from = "MANAGED_MIGRATIONS_ROLE_ARN")]
+ pub managed_migrations_role_arn: Option<String>,
+
// Dedicated root for temp files created during job processing. Swept on
// every startup to reclaim space leaked by non-graceful pod terminations.
#[envconfig(from = "STAGING_DIR", default = "/tmp/batch-import-worker")]
diff --git a/rust/batch-import-worker/src/job/config.rs b/rust/batch-import-worker/src/job/config.rs
index d99621d399fe..349aff7cd4ed 100644
--- a/rust/batch-import-worker/src/job/config.rs
+++ b/rust/batch-import-worker/src/job/config.rs
@@ -262,11 +262,19 @@ impl SourceConfig {
// may have been deleted, for example.
config.create_source(secrets, !is_restarting).await?,
)),
- SourceConfig::S3(config) => Ok(Box::new(config.create_source(secrets).await?)),
+ SourceConfig::S3(config) => Ok(Box::new(
+ config
+ .create_source(
+ secrets,
+ context.config.managed_migrations_role_arn.as_deref(),
+ )
+ .await?,
+ )),
SourceConfig::S3Gzip(config) => Ok(Box::new(
config
.create_gzip_source(
secrets,
+ context.config.managed_migrations_role_arn.as_deref(),
staging_dir,
staging_max_bytes,
staging_backend,
@@ -509,6 +517,7 @@ impl S3SourceConfig {
&self,
role_arn: &str,
external_id: &str,
+ managed_migrations_role_arn: Option<&str>,
) -> Result<aws_config::sts::AssumeRoleProvider, Error> {
if self.endpoint_url.is_some() {
return Err(Error::from(UserError::new(
@@ -516,14 +525,54 @@ impl S3SourceConfig {
)));
}
- let provider = aws_config::sts::AssumeRoleProvider::builder(role_arn)
+ let mut builder = aws_config::sts::AssumeRoleProvider::builder(role_arn)
.session_name("posthog-batch-import")
.external_id(external_id)
.region(Region::new(self.region.clone()))
.session_length(Duration::from_secs(3600))
- .policy(self.session_policy())
+ .policy(self.session_policy());
+
+ // Customer trust policies reference the dedicated managed-migrations role, not the
+ // worker's own identity, so chain through it: ambient creds -> managed-migrations
+ // role -> customer role. Without that role configured the customer hop can never
+ // succeed, so fail the job up front rather than attempting a direct assume that
+ // would pause it with a message wrongly blaming the customer's trust policy.
+ let Some(intermediate_arn) = managed_migrations_role_arn else {
+ return Err(Error::from(UserError::new(
+ "The PostHog import service is missing its cross-account role configuration, \
+ so it cannot use IAM role authentication. This is not a problem with your S3 \
+ or IAM setup. Please contact PostHog support.",
+ )));
+ };
+
+ let intermediate = aws_config::sts::AssumeRoleProvider::builder(intermediate_arn)
+ .session_name("posthog-batch-import")
+ .region(Region::new(self.region.clone()))
.build()
.await;
+ // An unassumable intermediate role is a PostHog deployment problem, so surface the
+ // same contact-support message as the missing-ARN case above rather than the
+ // customer-facing trust-policy message below. The ARN and STS error stay in the
+ // inner error chain for logs and status_message.
+ intermediate.provide_credentials().await.map_err(|e| {
+ Error::from(e)
+ .context(format!(
+ "Failed to assume managed-migrations role {intermediate_arn}"
+ ))
+ .context(UserError::new(
+ "PostHog's import service could not authenticate with its own cross-account \
+ role, so it cannot use IAM role authentication. This is not a problem with \
+ your S3 or IAM setup. Please contact PostHog support.",
+ ))
+ })?;
+ let chain_config = aws_config::defaults(BehaviorVersion::latest())
+ .region(Region::new(self.region.clone()))
+ .credentials_provider(intermediate)
+ .load()
+ .await;
+ builder = builder.configure(&chain_config);
+
+ let provider = builder.build().await;
// Fail fast so a misconfigured trust policy pauses the job with an actionable
// message instead of surfacing as an opaque S3 error mid-import.
@@ -539,6 +588,7 @@ impl S3SourceConfig {
async fn build_s3_config(
&self,
secrets: &JobSecrets,
+ managed_migrations_role_arn: Option<&str>,
) -> Result<aws_sdk_s3::config::Builder, Error> {
let mut builder = aws_sdk_s3::config::Builder::new()
.region(Region::new(self.region.clone()))
@@ -559,8 +609,10 @@ impl S3SourceConfig {
S3Auth::Role {
role_arn,
external_id,
- } => builder
- .credentials_provider(self.assume_role_credentials(role_arn, external_id).await?),
+ } => builder.credentials_provider(
+ self.assume_role_credentials(role_arn, external_id, managed_migrations_role_arn)
+ .await?,
+ ),
S3Auth::Keys {
access_key_id_key,
secret_access_key_key,
@@ -588,13 +640,25 @@ impl S3SourceConfig {
Ok(builder)
}
- async fn build_client(&self, secrets: &JobSecrets) -> Result<aws_sdk_s3::Client, Error> {
- let builder = self.build_s3_config(secrets).await?;
+ async fn build_client(
+ &self,
+ secrets: &JobSecrets,
+ managed_migrations_role_arn: Option<&str>,
+ ) -> Result<aws_sdk_s3::Client, Error> {
+ let builder = self
+ .build_s3_config(secrets, managed_migrations_role_arn)
+ .await?;
Ok(aws_sdk_s3::Client::from_conf(builder.build()))
}
- pub async fn create_source(&self, secrets: &JobSecrets) -> Result<S3Source, Error> {
- let client = self.build_client(secrets).await?;
+ pub async fn create_source(
+ &self,
+ secrets: &JobSecrets,
+ managed_migrations_role_arn: Option<&str>,
+ ) -> Result<S3Source, Error> {
+ let client = self
+ .build_client(secrets, managed_migrations_role_arn)
+ .await?;
Ok(S3Source::new(
client,
@@ -606,12 +670,15 @@ impl S3SourceConfig {
pub async fn create_gzip_source(
&self,
secrets: &JobSecrets,
+ managed_migrations_role_arn: Option<&str>,
staging_dir: PathBuf,
staging_max_bytes: u64,
staging_backend: Option<Arc<dyn StagingBackend>>,
staged_plaintext_max_bytes: u64,
) -> Result<GzipS3Source, Error> {
- let client = self.build_client(secrets).await?;
+ let client = self
+ .build_client(secrets, managed_migrations_role_arn)
+ .await?;
let remote_staging = staging_backend.map(|backend| RemoteStaging {
backend,
@@ -1057,19 +1124,30 @@ mod tests {
serde_json::json!({"endpoint_url": "https://acct123.r2.cloudflarestorage.com"}),
);
let err = config
- .build_s3_config(&empty_secrets())
+ .build_s3_config(&empty_secrets(), None)
.await
.unwrap_err()
.to_string();
assert!(err.contains("IAM role authentication only works with AWS S3"));
}
+ #[tokio::test]
+ async fn test_build_s3_config_rejects_role_auth_without_managed_migrations_role() {
+ let config = role_auth_config(serde_json::json!({}));
+ let err = config
+ .build_s3_config(&empty_secrets(), None)
+ .await
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("contact PostHog support"), "got: {err}");
+ }
+
#[tokio::test]
async fn test_build_s3_config_rejects_role_without_external_id() {
let mut config = role_auth_config(serde_json::json!({}));
config.external_id = None;
let err = config
- .build_s3_config(&empty_secrets())
+ .build_s3_config(&empty_secrets(), None)
.await
.unwrap_err()
.to_string();
@@ -1090,7 +1168,7 @@ mod tests {
secrets.insert("ak".to_string(), Value::String("key-id".to_string()));
secrets.insert("sk".to_string(), Value::String("key-secret".to_string()));
let secrets = JobSecrets { secrets };
- assert!(config.build_s3_config(&secrets).await.is_ok());
+ assert!(config.build_s3_config(&secrets, None).await.is_ok());
}
#[tokio::test]
@@ -1104,7 +1182,7 @@ mod tests {
}"#;
let config: S3SourceConfig = serde_json::from_str(json).unwrap();
let err = config
- .build_s3_config(&empty_secrets())
+ .build_s3_config(&empty_secrets(), None)
.await
.unwrap_err()
.to_string();
@@ -1123,7 +1201,7 @@ mod tests {
for patch in cases {
let config = role_auth_config(patch.clone());
let err = config
- .build_s3_config(&empty_secrets())
+ .build_s3_config(&empty_secrets(), None)
.await
.unwrap_err()
.to_string();
@@ -1146,7 +1224,7 @@ mod tests {
}"#;
let config: S3SourceConfig = serde_json::from_str(json).unwrap();
let err = config
- .build_s3_config(&empty_secrets())
+ .build_s3_config(&empty_secrets(), None)
.await
.unwrap_err()
.to_string();
@@ -1158,7 +1236,7 @@ mod tests {
let json = r#"{"bucket": "b", "prefix": "p", "region": "us-east-1"}"#;
let config: S3SourceConfig = serde_json::from_str(json).unwrap();
let err = config
- .build_s3_config(&empty_secrets())
+ .build_s3_config(&empty_secrets(), None)
.await
.unwrap_err()
.to_string();
diff --git a/rust/batch-import-worker/tests/s3_gzip_minio_integration_test.rs b/rust/batch-import-worker/tests/s3_gzip_minio_integration_test.rs
index 958c4d1cea0a..47f8d543a4c7 100644
--- a/rust/batch-import-worker/tests/s3_gzip_minio_integration_test.rs
+++ b/rust/batch-import-worker/tests/s3_gzip_minio_integration_test.rs
@@ -108,7 +108,7 @@ async fn test_s3_gzip_minio_integration() {
let _staging = tempfile::TempDir::new().expect("create staging dir");
let source = s3_config
- .create_gzip_source(&secrets, _staging.path().to_path_buf(), 0, None, 0)
+ .create_gzip_source(&secrets, None, _staging.path().to_path_buf(), 0, None, 0)
.await
.expect("create gzip source");
source.prepare_for_job().await.expect("prepare for job");