: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(batch-import-worker): user-supplied endpoint URL SSRF checks on Rust side (#59302)
Eli Reisman4257f9b9becb
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 09618cd67fb3..4c300c08a6c4 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -1262,6 +1262,7 @@ dependencies = ["async-trait","aws-config","aws-sdk-s3",+ "aws-smithy-http-client","axum 0.7.9","base64 0.22.1","bytes",@@ -1297,6 +1298,7 @@ dependencies = ["tokio-util","tracing","tracing-subscriber",+ "url","urlencoding","uuid","zip 4.6.1",@@ -2137,6 +2139,7 @@ dependencies = [name = "common-dns"version = "0.1.0"dependencies = [+ "aws-smithy-runtime-api","futures","reqwest 0.12.28","tokio",diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex 71d43f7179e3..c0d10cc994c8 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -160,6 +160,8 @@ quick_cache = "0.6.21"ahash = "0.8.11"aws-config = { version = "1.1.7", features = ["behavior-version-latest"] }aws-sdk-s3 = "1.58.0"+aws-smithy-runtime-api = { version = "1.11.5", features = ["client"] }+aws-smithy-http-client = { version = "1.1.11", features = ["rustls-aws-lc"] }mockall = "0.13.0"moka = { version = "0.12.15", features = ["sync", "future"] }posthog-rs = { version = "0.3.5", features = ["async-client"] }diff --git a/rust/batch-import-worker/Cargo.toml b/rust/batch-import-worker/Cargo.tomlindex 987d631f9fd7..a6daa8fbce4a 100644--- a/rust/batch-import-worker/Cargo.toml+++ b/rust/batch-import-worker/Cargo.toml@@ -21,7 +21,7 @@ common-kafka = { path = "../common/kafka" }common-alloc = { path = "../common/alloc" }common-types = { path = "../common/types" }common-metrics = { path = "../common/metrics" }-common-dns = { path = "../common/dns" }+common-dns = { path = "../common/dns", features = ["smithy"] }common-continuous-profiling = { path = "../common/continuous_profiling" }lifecycle = { path = "../common/lifecycle" }anyhow = { workspace = true }@@ -32,6 +32,7 @@ axum = { workspace = true }reqwest = { workspace = true }aws-config = { workspace = true }aws-sdk-s3 = { workspace = true }+aws-smithy-http-client = { workspace = true }rdkafka = { workspace = true }rayon = "1.10.0"celes = "=2.4.0"@@ -44,6 +45,7 @@ zip = "4.0.0"flate2.workspace = truehttpdate = "1"metrics = { workspace = true }+url = { workspace = true }urlencoding = "2.1"moka = { workspace = true }posthog-rs = { version = "0.4.2", features = ["async-client"] }diff --git a/rust/batch-import-worker/src/job/config.rs b/rust/batch-import-worker/src/job/config.rsindex 391f120ba916..414f17826b44 100644--- a/rust/batch-import-worker/src/job/config.rs+++ b/rust/batch-import-worker/src/job/config.rs@@ -1,4 +1,4 @@-use std::{collections::HashMap, sync::Arc, time::Duration};+use std::{collections::HashMap, net::IpAddr, sync::Arc, time::Duration};use anyhow::Error;use aws_config::{retry::RetryConfig, timeout::TimeoutConfig, BehaviorVersion, Region};@@ -79,6 +79,8 @@ pub struct S3SourceConfig {region: String,#[serde(default)]endpoint_url: Option<String>,+ #[serde(default)]+ allow_internal_ips: bool,}#[derive(Debug, Serialize, Deserialize, Clone)]@@ -300,7 +302,39 @@ impl UrlListConfig {}impl S3SourceConfig {- pub async fn create_source(&self, secrets: &JobSecrets) -> Result<S3Source, Error> {+ /// Reject endpoint URLs that point to private/internal IPs.+ /// Catches literal IP addresses that would bypass DNS-level SSRF protection.+ fn validate_endpoint_url(url: &str, allow_internal_ips: bool) -> Result<(), Error> {+ if allow_internal_ips {+ return Ok(());+ }++ let parsed = url::Url::parse(url)+ .map_err(|e| Error::msg(format!("Invalid endpoint URL '{}': {}", url, e)))?;++ let host = parsed+ .host()+ .ok_or_else(|| Error::msg(format!("Endpoint URL '{}' has no host", url)))?;++ let ip = match host {+ url::Host::Ipv4(v4) => Some(IpAddr::V4(v4)),+ url::Host::Ipv6(v6) => Some(IpAddr::V6(v6)),+ url::Host::Domain(_) => None,+ };++ if let Some(ip) = ip {+ if !common_dns::is_global_ip(&ip) {+ return Err(Error::msg(format!(+ "Endpoint URL '{}' resolves to non-public IP address",+ url+ )));+ }+ }++ Ok(())+ }++ fn build_s3_config(&self, secrets: &JobSecrets) -> Result<aws_sdk_s3::config::Builder, Error> {let access_key_id = secrets.secrets.get(&self.access_key_id_key)@@ -345,9 +379,26 @@ impl S3SourceConfig {.build(),).retry_config(RetryConfig::standard());+if let Some(ref url) = self.endpoint_url {+ Self::validate_endpoint_url(url, self.allow_internal_ips)?;builder = builder.endpoint_url(url).force_path_style(true);++ if !self.allow_internal_ips {+ let http_client = aws_smithy_http_client::Builder::new()+ .tls_provider(aws_smithy_http_client::tls::Provider::Rustls(+ aws_smithy_http_client::tls::rustls_provider::CryptoMode::AwsLc,+ ))+ .build_with_resolver(common_dns::PublicIPv4SmithyResolver);+ builder = builder.http_client(http_client);+ }}++ Ok(builder)+ }++ pub async fn create_source(&self, secrets: &JobSecrets) -> Result<S3Source, Error> {+ let builder = self.build_s3_config(secrets)?;let client = aws_sdk_s3::Client::from_conf(builder.build());Ok(S3Source::new(@@ -358,53 +409,7 @@ impl S3SourceConfig {}pub async fn create_gzip_source(&self, secrets: &JobSecrets) -> Result<GzipS3Source, Error> {- let access_key_id = secrets- .secrets- .get(&self.access_key_id_key)- .ok_or(Error::msg(format!(- "Missing access key id as key {}",- self.access_key_id_key- )))?- .as_str()- .ok_or(Error::msg(format!(- "Access key id as key {} is not a string",- self.access_key_id_key- )))?;-- let secret_access_key = secrets- .secrets- .get(&self.secret_access_key_key)- .ok_or(Error::msg(format!(- "Missing secret access key as key {}",- self.secret_access_key_key- )))?- .as_str()- .ok_or(Error::msg(format!(- "Secret access key as key {} is not a string",- self.secret_access_key_key- )))?;-- let aws_credentials = aws_sdk_s3::config::Credentials::new(- access_key_id,- secret_access_key,- None,- None,- "job_config",- );-- let mut builder = aws_sdk_s3::config::Builder::new()- .region(Region::new(self.region.clone()))- .credentials_provider(aws_credentials)- .behavior_version(BehaviorVersion::latest())- .timeout_config(- TimeoutConfig::builder()- .operation_timeout(Duration::from_secs(30))- .build(),- )- .retry_config(RetryConfig::standard());- if let Some(ref url) = self.endpoint_url {- builder = builder.endpoint_url(url).force_path_style(true);- }+ let builder = self.build_s3_config(secrets)?;let client = aws_sdk_s3::Client::from_conf(builder.build());Ok(GzipS3Source::new(@@ -792,6 +797,82 @@ mod tests {}}+ #[test]+ fn test_s3_source_config_allow_internal_ips_defaults_false() {+ let json = r#"{+ "access_key_id_key": "ak",+ "secret_access_key_key": "sk",+ "bucket": "b",+ "prefix": "p",+ "region": "us-east-1"+ }"#;+ let config: S3SourceConfig = serde_json::from_str(json).unwrap();+ assert!(!config.allow_internal_ips);+ }++ #[test]+ fn test_s3_source_config_allow_internal_ips_explicit_true() {+ let json = r#"{+ "access_key_id_key": "ak",+ "secret_access_key_key": "sk",+ "bucket": "b",+ "prefix": "p",+ "region": "us-east-1",+ "allow_internal_ips": true+ }"#;+ let config: S3SourceConfig = serde_json::from_str(json).unwrap();+ assert!(config.allow_internal_ips);+ }++ #[test]+ fn test_validate_endpoint_url_rejects_metadata_service() {+ let result = S3SourceConfig::validate_endpoint_url("http://169.254.169.254", false);+ assert!(result.is_err());+ assert!(result+ .unwrap_err()+ .to_string()+ .contains("non-public IP address"));+ }++ #[test]+ fn test_validate_endpoint_url_rejects_private_ip() {+ let result = S3SourceConfig::validate_endpoint_url("http://10.0.0.1:9000", false);+ assert!(result.is_err());+ }++ #[test]+ fn test_validate_endpoint_url_rejects_loopback() {+ let result = S3SourceConfig::validate_endpoint_url("http://127.0.0.1:9000", false);+ assert!(result.is_err());+ }++ #[test]+ fn test_validate_endpoint_url_rejects_ipv6_loopback() {+ let result = S3SourceConfig::validate_endpoint_url("http://[::1]:9000", false);+ assert!(result.is_err());+ }++ #[test]+ fn test_validate_endpoint_url_accepts_public_hostname() {+ let result = S3SourceConfig::validate_endpoint_url(+ "https://acct123.r2.cloudflarestorage.com",+ false,+ );+ assert!(result.is_ok());+ }++ #[test]+ fn test_validate_endpoint_url_accepts_internal_when_allowed() {+ let result = S3SourceConfig::validate_endpoint_url("http://localhost:9000", true);+ assert!(result.is_ok());+ }++ #[test]+ fn test_validate_endpoint_url_rejects_invalid_url() {+ let result = S3SourceConfig::validate_endpoint_url("not-a-url", false);+ assert!(result.is_err());+ }+#[test]fn test_sink_config_serialization() {// Test SinkConfig serialization with different variantsdiff --git a/rust/batch-import-worker/tests/s3_gzip_minio_integration_test.rs b/rust/batch-import-worker/tests/s3_gzip_minio_integration_test.rsindex d7ae7f73625a..155c39ffe018 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@@ -91,7 +91,8 @@ async fn test_s3_gzip_minio_integration() {"bucket": TEST_BUCKET,"prefix": prefix,"region": "us-east-1",- "endpoint_url": MINIO_ENDPOINT+ "endpoint_url": MINIO_ENDPOINT,+ "allow_internal_ips": true})).expect("source config from json");let s3_config = match &source_config {diff --git a/rust/common/dns/Cargo.toml b/rust/common/dns/Cargo.tomlindex b67a2d04e63a..354f95d86e14 100644--- a/rust/common/dns/Cargo.toml+++ b/rust/common/dns/Cargo.toml@@ -6,7 +6,11 @@ edition = "2021"[lints]workspace = true+[features]+smithy = ["aws-smithy-runtime-api"]+[dependencies]+aws-smithy-runtime-api = { workspace = true, optional = true }futures = { workspace = true }reqwest = { workspace = true }tokio = { workspace = true }\ No newline at end of filediff --git a/rust/common/dns/src/lib.rs b/rust/common/dns/src/lib.rsindex 120474372575..8a383b254349 100644--- a/rust/common/dns/src/lib.rs+++ b/rust/common/dns/src/lib.rs@@ -23,11 +23,11 @@ impl fmt::Debug for NoPublicIPv4Error {/// Internal reqwest type, copied here as part of Resolvingpub(crate) type BoxError = Box<dyn StdError + Send + Sync>;-/// Returns [`true`] if the address appears to be a globally reachable IPv4.+/// Returns [`true`] if the IP appears to be a globally reachable IPv4.////// Trimmed down version of the unstable IpAddr::is_global, move to it when it's stable.-fn is_global_ipv4(addr: &SocketAddr) -> bool {- match addr.ip() {+pub fn is_global_ip(ip: &IpAddr) -> bool {+ match ip {IpAddr::V4(ip) => {!(ip.octets()[0] == 0 // "This network"|| ip.is_private()@@ -39,6 +39,10 @@ fn is_global_ipv4(addr: &SocketAddr) -> bool {}}+fn is_global_ipv4(addr: &SocketAddr) -> bool {+ is_global_ip(&addr.ip())+}+/// DNS resolver using the stdlib resolver, but filtering results to only pass public IPv4 results.////// Private and broadcast addresses are filtered out, so are IPv6 results for now (as our infra@@ -84,6 +88,46 @@ impl Resolve for PublicIPv4Resolver {}}+/// DNS resolver for the AWS Smithy SDK, filtering to public IPv4 only.+///+/// Same logic as [`PublicIPv4Resolver`] (which targets reqwest), but implements+/// [`aws_smithy_runtime_api::client::dns::ResolveDns`] for use with the AWS SDK S3 client.+/// Gated behind the `smithy` feature to avoid pulling AWS SDK deps into unrelated consumers.+#[cfg(feature = "smithy")]+#[derive(Debug, Clone)]+pub struct PublicIPv4SmithyResolver;++#[cfg(feature = "smithy")]+impl aws_smithy_runtime_api::client::dns::ResolveDns for PublicIPv4SmithyResolver {+ fn resolve_dns<'a>(+ &'a self,+ name: &'a str,+ ) -> aws_smithy_runtime_api::client::dns::DnsFuture<'a> {+ use aws_smithy_runtime_api::client::dns::{DnsFuture, ResolveDnsError};++ let name = name.to_string();+ DnsFuture::new(async move {+ let resolve_host =+ move || std::net::ToSocketAddrs::to_socket_addrs(&(name.as_str(), 0));++ let result = tokio::task::spawn_blocking(resolve_host)+ .await+ .map_err(|e| ResolveDnsError::new(io::Error::from(e)))?;++ let all_addrs = result.map_err(ResolveDnsError::new)?;++ let filtered: Vec<std::net::IpAddr> =+ all_addrs.filter(is_global_ipv4).map(|sa| sa.ip()).collect();++ if filtered.is_empty() {+ Err(ResolveDnsError::new(NoPublicIPv4Error))+ } else {+ Ok(filtered)+ }+ })+ }+}+#[cfg(test)]mod tests {use crate::{NoPublicIPv4Error, PublicIPv4Resolver};@@ -138,3 +182,46 @@ mod tests {}}}++#[cfg(all(test, feature = "smithy"))]+mod smithy_tests {+ use crate::PublicIPv4SmithyResolver;+ use aws_smithy_runtime_api::client::dns::ResolveDns;++ #[tokio::test]+ async fn smithy_resolves_google_com() {+ let resolver = PublicIPv4SmithyResolver;+ let addrs = resolver+ .resolve_dns("google.com")+ .await+ .expect("lookup has failed");+ assert!(!addrs.is_empty(), "empty address list");+ }++ #[tokio::test]+ async fn smithy_denies_localhost() {+ let resolver = PublicIPv4SmithyResolver;+ let err = resolver+ .resolve_dns("localhost")+ .await+ .expect_err("should have rejected localhost");+ assert!(+ err.to_string().contains("DNS") || format!("{:?}", err).contains("NoPublicIPv4Error"),+ "unexpected error: {err:?}"+ );+ }++ #[tokio::test]+ async fn smithy_bubbles_up_resolution_error() {+ let resolver = PublicIPv4SmithyResolver;+ let err = resolver+ .resolve_dns("invalid.domain.unknown")+ .await+ .expect_err("should have failed");+ let debug = format!("{:?}", err);+ assert!(+ debug.contains("lookup address") || debug.contains("DNS"),+ "unexpected error: {debug}"+ );+ }+}