: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
fix(error-tracking): decompress fetched javascript assets (#71066)
Hugues Pouillot36ad403a755a
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 1615cf0d3bc9..45e144891f47 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2866,6 +2866,7 @@ dependencies = ["bytes","chrono","common-alloc",+ "common-compression","common-continuous-profiling","common-database","common-dns",diff --git a/rust/cymbal/Cargo.toml b/rust/cymbal/Cargo.tomlindex b68154acebf7..b90c8c317da7 100644--- a/rust/cymbal/Cargo.toml+++ b/rust/cymbal/Cargo.toml@@ -33,7 +33,7 @@ sourcemap = "9.0.0"symbolic = { version = "12.12", features = ["sourcemapcache", "debuginfo", "symcache", "demangle"] }zip = "4.0"proguard = "5.6.2"-reqwest = { workspace = true }+reqwest = { workspace = true, features = ["brotli", "deflate", "gzip", "zstd"] }sha2 = "0.10.8"semver = "1.0"aws-config = { workspace = true }@@ -58,6 +58,7 @@ subtle = "2.6"[dev-dependencies]+common-compression = { path = "../common/compression" }httpmock = { workspace = true }mockall = { workspace = true }insta = { version = "1.46.0", features = ["json", "redactions"] }diff --git a/rust/cymbal/README.md b/rust/cymbal/README.mdindex 3352c4310d15..dfc3d5fa618f 100644--- a/rust/cymbal/README.md+++ b/rust/cymbal/README.md@@ -53,6 +53,8 @@ See [`docs/compatibility.md`](docs/compatibility.md) for the Node consumercompatibility checklist and [`src/modes/resolution/README.md`](src/modes/resolution/README.md)for rollout and dashboard guidance.+Fetched JavaScript sources and external source maps are limited to 25 MB after HTTP decompression by default. Set `SOURCEMAP_MAX_RESPONSE_BYTES` to adjust this limit.+### TermsWe use a lot of terms in this and other error tracking code, with implied meanings. Here are some of them:diff --git a/rust/cymbal/src/core/config.rs b/rust/cymbal/src/core/config.rsindex 49f50b1a5dec..00922cbb7d0c 100644--- a/rust/cymbal/src/core/config.rs+++ b/rust/cymbal/src/core/config.rs@@ -28,6 +28,9 @@ pub struct ResolverConfig {#[envconfig(default = "5")]pub sourcemap_connect_timeout_seconds: u64,+ #[envconfig(default = "25000000")]+ pub sourcemap_max_response_bytes: usize,+#[envconfig(default = "100000000")] // 100MB - in prod, we should use closer to 1-10GBpub symbol_store_cache_max_bytes: usize,diff --git a/rust/cymbal/src/core/symbolication/symbol_store/sourcemap.rs b/rust/cymbal/src/core/symbolication/symbol_store/sourcemap.rsindex 863b279eea35..9f65a15a7190 100644--- a/rust/cymbal/src/core/symbolication/symbol_store/sourcemap.rs+++ b/rust/cymbal/src/core/symbolication/symbol_store/sourcemap.rs@@ -3,6 +3,7 @@ use std::{collections::HashMap, sync::Arc, time::Duration};use async_trait::async_trait;use base64::Engine;use bytes::Bytes;+use futures::StreamExt;use posthog_symbol_data::{read_symbol_data_with_byte_count, write_symbol_data, SourceAndMap};use reqwest::Url;use sqlx::PgPool;@@ -29,6 +30,7 @@ use super::{pub struct SourcemapProvider {pub client: reqwest::Client,pub chunk_id_rescue: Option<ChunkIdRescue>,+ pub max_response_bytes: usize,}#[derive(Clone)]@@ -138,6 +140,7 @@ impl SourcemapProvider {Self {client,chunk_id_rescue: None,+ max_response_bytes: config.sourcemap_max_response_bytes,}}@@ -175,7 +178,7 @@ impl Fetcher for SourcemapProvider {type Err = ResolveError;async fn fetch(&self, team_id: i32, r: Url) -> Result<Bytes, Self::Err> {let start = common_metrics::timing_guard(SOURCEMAP_FETCH, &[]);- let peek = find_sourcemap_url(&self.client, r).await?;+ let peek = find_sourcemap_url(&self.client, r, self.max_response_bytes).await?;let start = start.label("found_url", "true");@@ -193,7 +196,8 @@ impl Fetcher for SourcemapProvider {let sourcemap = match peek.sourcemap_url {SourceMappingUrl::Url(sourcemap_url) => {- fetch_source_map(&self.client, sourcemap_url.clone()).await?+ fetch_source_map(&self.client, sourcemap_url.clone(), self.max_response_bytes)+ .await?}SourceMappingUrl::Data(data) => data,};@@ -306,6 +310,7 @@ fn extract_chunk_id_from_body(body: &str) -> Option<String> {async fn find_sourcemap_url(client: &reqwest::Client,start: Url,+ max_response_bytes: usize,) -> Result<JsSourcePeek, ResolveError> {info!("Fetching script source from {}", start);@@ -330,7 +335,7 @@ async fn find_sourcemap_url(.cloned();// We always need the body- let body = res.text().await.map_err(JsResolveErr::from)?;+ let body = read_response_text_limited(res, &final_url, max_response_bytes).await?;metrics::histogram!(SOURCEMAP_EXTERNAL_BYTES, "kind" => "source").record(body.len() as f64);let chunk_id_from_body = extract_chunk_id_from_body(&body);@@ -370,8 +375,12 @@ async fn find_sourcemap_url(let found = line.trim_start_matches("//# sourceMappingURL=");// If we can parse this as a data URL, we can just use that- if let Some(data) = maybe_as_data_url(final_url.as_ref(), found, data_url_to_json_str)?- {+ if let Some(data) = maybe_as_data_url(+ final_url.as_ref(),+ found,+ max_response_bytes,+ data_url_to_json_str,+ )? {return Ok(JsSourcePeek {body,sourcemap_url: SourceMappingUrl::Data(data),@@ -432,16 +441,49 @@ async fn find_sourcemap_url(Err(JsResolveErr::NoSourcemap(final_url.to_string()).into())}-async fn fetch_source_map(client: &reqwest::Client, url: Url) -> Result<String, ResolveError> {+async fn fetch_source_map(+ client: &reqwest::Client,+ url: Url,+ max_response_bytes: usize,+) -> Result<String, ResolveError> {metrics::counter!(SOURCEMAP_BODY_FETCHES).increment(1);let res = client.get(url).send().await.map_err(JsResolveErr::from)?;res.error_for_status_ref().map_err(JsResolveErr::from)?;- let sourcemap = res.text().await.map_err(JsResolveErr::from)?;+ let final_url = res.url().clone();+ let sourcemap = read_response_text_limited(res, &final_url, max_response_bytes).await?;metrics::histogram!(SOURCEMAP_EXTERNAL_BYTES, "kind" => "sourcemap").record(sourcemap.len() as f64);Ok(sourcemap)}+async fn read_response_text_limited(+ response: reqwest::Response,+ url: &Url,+ max_response_bytes: usize,+) -> Result<String, ResolveError> {+ let mut body = Vec::with_capacity(+ response+ .content_length()+ .and_then(|length| usize::try_from(length).ok())+ .unwrap_or_default()+ .min(max_response_bytes),+ );+ let mut stream = response.bytes_stream();++ while let Some(chunk) = stream.next().await {+ let chunk = chunk.map_err(JsResolveErr::from)?;+ if body.len().saturating_add(chunk.len()) > max_response_bytes {+ return Err(JsResolveErr::NetworkError(format!(+ "Response from {url} exceeded the {max_response_bytes} byte limit"+ ))+ .into());+ }+ body.extend_from_slice(&chunk);+ }++ Ok(String::from_utf8_lossy(&body).into_owned())+}+// Below as per https://developer.mozilla.org/en-US/docs/Web/URI/Reference/Schemes/dataconst DATA_SCHEME: &str = "data:";@@ -454,6 +496,7 @@ struct DataUrlContent {fn maybe_as_data_url<T>(source_url: &str,data: &str,+ max_response_bytes: usize,parse_fn: impl FnOnce(DataUrlContent) -> Result<T, ResolveError>,) -> Result<Option<T>, ResolveError> {if !data.starts_with(DATA_SCHEME) {@@ -526,6 +569,13 @@ fn maybe_as_data_url<T>(}};+ if data.len() > max_response_bytes {+ return Err(JsResolveErr::NetworkError(format!(+ "Response from {source_url} exceeded the {max_response_bytes} byte limit"+ ))+ .into());+ }+let mime_type = mime_type.to_string();let content = DataUrlContent { data, mime_type };@@ -561,12 +611,14 @@ fn assert_is_sourcemap(data: &str) -> Result<(), ResolveError> {#[cfg(test)]mod test {+ use crate::error::FrameError;use httpmock::MockServer;const MINIFIED: &[u8] = include_bytes!("../../../../tests/static/chunk-PGUQKT6S.js");const MAP: &[u8] = include_bytes!("../../../../tests/static/chunk-PGUQKT6S.js.map");const MINIFIED_WITH_NO_MAP_REF: &[u8] =include_bytes!("../../../../tests/static/chunk-PGUQKT6S-no-map.js");+ const TEST_MAX_RESPONSE_BYTES: usize = 25_000_000;use super::*;@@ -581,7 +633,9 @@ mod test {let client = reqwest::Client::new();let url = server.url("/static/chunk-PGUQKT6S.js").parse().unwrap();- let peek = find_sourcemap_url(&client, url).await.unwrap();+ let peek = find_sourcemap_url(&client, url, TEST_MAX_RESPONSE_BYTES)+ .await+ .unwrap();let SourceMappingUrl::Url(res) = peek.sourcemap_url else {panic!("Expected URL, got something else");@@ -593,6 +647,99 @@ mod test {mock.assert_hits(1);}+ #[tokio::test]+ async fn fetch_decompresses_gzip_source() {+ let server = MockServer::start();+ let compressed = common_compression::compress_gzip(MINIFIED).unwrap();++ let source_mock = server.mock(|when, then| {+ when.method("GET").path("/static/chunk-PGUQKT6S.js");+ then.status(200)+ .header("Content-Encoding", "gzip")+ .body(compressed);+ });+ let map_mock = server.mock(|when, then| {+ when.method("GET").path("/static/chunk-PGUQKT6S.js.map");+ then.status(200).body(MAP);+ });++ let mut config = ResolverConfig::init_with_defaults().unwrap();+ config.allow_internal_ips = true;+ let provider = SourcemapProvider::new(&config);+ let url = server.url("/static/chunk-PGUQKT6S.js").parse().unwrap();+ let data = provider.fetch(1, url).await.unwrap();+ let (source_and_map, _): (SourceAndMap, usize) =+ read_symbol_data_with_byte_count(&data).unwrap();++ assert_eq!(source_and_map.minified_source.as_bytes(), MINIFIED);+ source_mock.assert_hits(1);+ map_mock.assert_hits(1);+ }++ #[tokio::test]+ async fn fetch_rejects_oversized_compressed_source() {+ let server = MockServer::start();+ let compressed = common_compression::compress_gzip(&vec![b'a'; 1024]).unwrap();++ let source_mock = server.mock(|when, then| {+ when.method("GET").path("/static/oversized.js");+ then.status(200)+ .header("Content-Encoding", "gzip")+ .body(compressed);+ });++ let mut config = ResolverConfig::init_with_defaults().unwrap();+ config.allow_internal_ips = true;+ config.sourcemap_max_response_bytes = 128;+ let provider = SourcemapProvider::new(&config);+ let url = server.url("/static/oversized.js").parse().unwrap();++ let error = provider.fetch(1, url).await.unwrap_err();++ assert!(matches!(+ error,+ ResolveError::ResolutionError(FrameError::JavaScript(JsResolveErr::NetworkError(+ message+ ))) if message.contains("exceeded the 128 byte limit")+ ));+ source_mock.assert_hits(1);+ }++ #[tokio::test]+ async fn fetch_rejects_oversized_compressed_sourcemap() {+ let server = MockServer::start();+ let source = "console.log('hello');\n//# sourceMappingURL=oversized.js.map\n";+ let compressed_map = common_compression::compress_gzip(&vec![b'a'; 1024]).unwrap();++ let source_mock = server.mock(|when, then| {+ when.method("GET").path("/static/oversized.js");+ then.status(200).body(source);+ });+ let map_mock = server.mock(|when, then| {+ when.method("GET").path("/static/oversized.js.map");+ then.status(200)+ .header("Content-Encoding", "gzip")+ .body(compressed_map);+ });++ let mut config = ResolverConfig::init_with_defaults().unwrap();+ config.allow_internal_ips = true;+ config.sourcemap_max_response_bytes = 128;+ let provider = SourcemapProvider::new(&config);+ let url = server.url("/static/oversized.js").parse().unwrap();++ let error = provider.fetch(1, url).await.unwrap_err();++ assert!(matches!(+ error,+ ResolveError::ResolutionError(FrameError::JavaScript(JsResolveErr::NetworkError(+ message+ ))) if message.contains("exceeded the 128 byte limit")+ ));+ source_mock.assert_hits(1);+ map_mock.assert_hits(1);+ }+#[tokio::test]async fn full_follows_links_test() {let server = MockServer::start();@@ -673,7 +820,9 @@ mod test {.url("/static/inline_sourcemap_example.js").parse().unwrap();- let peek = find_sourcemap_url(&client, url).await.unwrap();+ let peek = find_sourcemap_url(&client, url, TEST_MAX_RESPONSE_BYTES)+ .await+ .unwrap();let SourceMappingUrl::Data(res) = peek.sourcemap_url else {panic!("Expected Data, got something else");@@ -686,6 +835,24 @@ mod test {mock.assert_hits(1);}+ #[test]+ fn data_url_rejects_decoded_payload_over_limit() {+ let error = maybe_as_data_url(+ "https://example.com/chunk.js",+ "data:application/json;base64,eHh4eHh4eHg=",+ 4,+ data_url_to_json_str,+ )+ .unwrap_err();++ assert!(matches!(+ error,+ ResolveError::ResolutionError(FrameError::JavaScript(JsResolveErr::NetworkError(+ message+ ))) if message.contains("exceeded the 4 byte limit")+ ));+ }+#[test]fn extract_chunk_id_from_body_handles_known_prefixes() {let canonical =