: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): protect symbol set storage from poisoning (#59442)
Hugues Pouillotfdfee5a600be
diff --git a/rust/cymbal/src/langs/apple.rs b/rust/cymbal/src/langs/apple.rsindex e7eb118524e3..812d3951ae6f 100644--- a/rust/cymbal/src/langs/apple.rs+++ b/rust/cymbal/src/langs/apple.rs@@ -135,7 +135,10 @@ impl RawAppleFrame {))])}Err(ResolveError::ResolutionError(e)) => {- unreachable!("Should not have received error {:?}", e)+ tracing::warn!("Unexpected Apple symbol resolution error: {:?}", e);+ Ok(vec![self.handle_resolution_error(AppleError::ParseError(+ e.to_string(),+ ))])}Err(ResolveError::UnhandledError(e)) => {tracing::error!("[apple-debug] resolve() unhandled error: {:?}", e);diff --git a/rust/cymbal/src/langs/hermes.rs b/rust/cymbal/src/langs/hermes.rsindex de4b5fb2ed43..eb87336afaa6 100644--- a/rust/cymbal/src/langs/hermes.rs+++ b/rust/cymbal/src/langs/hermes.rs@@ -54,8 +54,8 @@ impl RawHermesFrame {Ok(self.handle_resolution_error(HermesError::NoSourcemapUploaded(chunk_id)))}Err(ResolveError::ResolutionError(e)) => {- // TODO - other kinds of errors here should be unreachable, we need to specialize ResolveError to encode that- unreachable!("Should not have received error {:?}", e)+ tracing::warn!("Unexpected Hermes symbol resolution error: {:?}", e);+ Ok(self.handle_resolution_error(HermesError::InvalidMap(e.to_string())))}Err(ResolveError::UnhandledError(e)) => Err(e),}diff --git a/rust/cymbal/src/langs/java.rs b/rust/cymbal/src/langs/java.rsindex 847e95b7c5df..9c04495e3e04 100644--- a/rust/cymbal/src/langs/java.rs+++ b/rust/cymbal/src/langs/java.rs@@ -66,8 +66,10 @@ impl RawJavaFrame {vec![self.handle_resolution_error(ProguardError::MissingMap(chunk_id))],),Err(ResolveError::ResolutionError(e)) => {- // TODO - other kinds of errors here should be unreachable, we need to specialize ResolveError to encode that- unreachable!("Should not have received error {:?}", e)+ warn!("Unexpected Proguard symbol resolution error: {:?}", e);+ Ok(vec![+ self.handle_resolution_error(ProguardError::InvalidMapping)+ ])}Err(ResolveError::UnhandledError(e)) => Err(e),}diff --git a/rust/cymbal/src/langs/js.rs b/rust/cymbal/src/langs/js.rsindex b94978bd62f3..3a4e9c9c68a1 100644--- a/rust/cymbal/src/langs/js.rs+++ b/rust/cymbal/src/langs/js.rs@@ -3,6 +3,7 @@ use reqwest::Url;use serde::{Deserialize, Serialize};use sha2::{Digest, Sha512};use symbolic::sourcemapcache::{ScopeLookupResult, SourceLocation, SourcePosition};+use tracing::warn;use crate::{error::{FrameError, JsResolveErr, ResolveError, UnhandledError},@@ -52,8 +53,8 @@ impl RawJSFrame {Ok(self.handle_resolution_error(JsResolveErr::NoSourcemapUploaded(chunk_id)))}Err(ResolveError::ResolutionError(e)) => {- // TODO - other kinds of errors here should be unreachable, we need to specialize ResolveError to encode that- unreachable!("Should not have received error {:?}", e)+ warn!("Unexpected JS symbol resolution error: {:?}", e);+ Ok(self.handle_resolution_error(JsResolveErr::InvalidSourceMap(e.to_string())))}Err(ResolveError::UnhandledError(e)) => Err(e),}diff --git a/rust/cymbal/src/langs/node.rs b/rust/cymbal/src/langs/node.rsindex 6dd76bb557c2..8d3465775eec 100644--- a/rust/cymbal/src/langs/node.rs+++ b/rust/cymbal/src/langs/node.rs@@ -10,6 +10,7 @@ use reqwest::Url;use serde::{Deserialize, Serialize};use sha2::{Digest, Sha512};use symbolic::sourcemapcache::{ScopeLookupResult, SourceLocation, SourcePosition};+use tracing::warn;use super::{js::FrameLocation,@@ -50,8 +51,8 @@ impl RawNodeFrame {Ok((self, JsResolveErr::NoSourcemapUploaded(chunk_id)).into())}Err(ResolveError::ResolutionError(e)) => {- // TODO - other kinds of errors here should be unreachable, we need to specialize ResolveError to encode that- unreachable!("Should not have received error {:?}", e)+ warn!("Unexpected Node.js symbol resolution error: {:?}", e);+ Ok((self, JsResolveErr::InvalidSourceMap(e.to_string())).into())}Err(ResolveError::UnhandledError(e)) => Err(e),}diff --git a/rust/cymbal/src/symbol_store/s3.rs b/rust/cymbal/src/symbol_store/s3.rsindex ab34dfa23ebc..d1719a72e3e5 100644--- a/rust/cymbal/src/symbol_store/s3.rs+++ b/rust/cymbal/src/symbol_store/s3.rs@@ -15,6 +15,7 @@ use crate::{pub trait BlobClient: Send + Sync {async fn get(&self, bucket: &str, key: &str) -> Result<Option<Bytes>, UnhandledError>;async fn put(&self, bucket: &str, key: &str, data: Bytes) -> Result<(), UnhandledError>;+ async fn delete(&self, bucket: &str, key: &str) -> Result<(), UnhandledError>;async fn ping_bucket(&self, bucket: &str) -> Result<(), UnhandledError>;}@@ -93,6 +94,18 @@ impl BlobClient for S3Impl {res}+ #[allow(dead_code)]+ async fn delete(&self, bucket: &str, key: &str) -> Result<(), UnhandledError> {+ self.inner+ .delete_object()+ .bucket(bucket)+ .key(key)+ .send()+ .await+ .map_err(|e| S3Error::from(e).into())+ .map(|_| ())+ }+// Simply assert we can do a ListBucket operation, returning an error if not. This is// useful during app startup to ensure the bucket is accessible.#[allow(dead_code)]diff --git a/rust/cymbal/src/symbol_store/saving.rs b/rust/cymbal/src/symbol_store/saving.rsindex 9e5cd1a8fdce..2856f60cc5e6 100644--- a/rust/cymbal/src/symbol_store/saving.rs+++ b/rust/cymbal/src/symbol_store/saving.rs@@ -116,7 +116,20 @@ impl<F> Saving<F> {};self.s3_client.put(&self.bucket, &key, data).await?;- record.save(&self.pool).await?;+ if !record.save_data_if_missing(&self.pool).await? {+ warn!(+ "Not overwriting existing symbol set data for {} after dynamic fetch",+ record.set_ref+ );+ if let Err(err) = self.s3_client.delete(&self.bucket, &key).await {+ warn!(+ "Failed to clean up unused symbol set data at {} after skipped DB update: {:?}",+ key, err+ );+ }+ start.label("outcome", "skipped_existing_data").fin();+ return Ok(key);+ }// We just saved new data for this symbol set, which invalidates all our previous stack frame resolution results,// so delete themlet deleted: u64 = sqlx::query_scalar!(@@ -148,7 +161,7 @@ impl<F> Saving<F> {) -> Result<(), UnhandledError> {info!("Saving symbol set error for {}", set_ref);let start = common_metrics::timing_guard(SAVE_SYMBOL_SET, &[]).label("data", "false");- SymbolSetRecord {+ let mut record = SymbolSetRecord {id: Uuid::now_v7(),team_id,set_ref,@@ -157,9 +170,8 @@ impl<F> Saving<F> {created_at: Utc::now(),content_hash: None,last_used: Some(Utc::now()),- }- .save(&self.pool)- .await?;+ };+ record.save_failure(&self.pool).await?;start.label("outcome", "success").fin();Ok(())}@@ -293,8 +305,11 @@ where}Err(ResolveError::ResolutionError(e)) => {info!("Failed to parse symbol set data for {}", set_ref);- // We save the no-data case here, to prevent us from fetching again for a day- self.save_no_data(team_id, set_ref, &e).await?;+ if storage_ptr.is_none() {+ // Save fresh parse failures to prevent refetching for a day, but never+ // replace an existing uploaded blob with a parser error.+ self.save_no_data(team_id, set_ref, &e).await?;+ }Err(ResolveError::ResolutionError(e))}Err(e) => Err(e),@@ -389,6 +404,72 @@ impl SymbolSetRecord {Ok(())}+ pub async fn save_data_if_missing<'c, E>(&mut self, e: E) -> Result<bool, UnhandledError>+ where+ E: sqlx::Executor<'c, Database = sqlx::Postgres>,+ {+ let truncated_ref = truncate_ref(&self.set_ref);+ let id = sqlx::query_scalar::<_, Uuid>(+ r#"+ INSERT INTO posthog_errortrackingsymbolset (id, team_id, ref, storage_ptr, failure_reason, created_at, content_hash, last_used)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)+ ON CONFLICT (team_id, ref) DO UPDATE+ SET storage_ptr = $4, content_hash = $7, failure_reason = $5, last_used = $8+ WHERE posthog_errortrackingsymbolset.storage_ptr IS NULL+ RETURNING id+ "#,+ )+ .bind(self.id)+ .bind(self.team_id)+ .bind(truncated_ref)+ .bind(&self.storage_ptr)+ .bind(&self.failure_reason)+ .bind(self.created_at)+ .bind(&self.content_hash)+ .bind(self.last_used)+ .fetch_optional(e)+ .await?;++ if let Some(id) = id {+ self.id = id;+ metrics::counter!(SYMBOL_SET_SAVED).increment(1);+ return Ok(true);+ }++ Ok(false)+ }++ pub async fn save_failure<'c, E>(&mut self, e: E) -> Result<(), UnhandledError>+ where+ E: sqlx::Executor<'c, Database = sqlx::Postgres>,+ {+ let truncated_ref = truncate_ref(&self.set_ref);+ if let Some(id) = sqlx::query_scalar::<_, Uuid>(+ r#"+ INSERT INTO posthog_errortrackingsymbolset (id, team_id, ref, storage_ptr, failure_reason, created_at, content_hash, last_used)+ VALUES ($1, $2, $3, NULL, $4, $5, NULL, $6)+ ON CONFLICT (team_id, ref) DO UPDATE+ SET failure_reason = $4, last_used = $6+ WHERE posthog_errortrackingsymbolset.storage_ptr IS NULL+ RETURNING id+ "#,+ )+ .bind(self.id)+ .bind(self.team_id)+ .bind(truncated_ref)+ .bind(&self.failure_reason)+ .bind(self.created_at)+ .bind(self.last_used)+ .fetch_optional(e)+ .await?+ {+ self.id = id;+ metrics::counter!(SYMBOL_SET_SAVED).increment(1);+ }++ Ok(())+ }+pub async fn delete<'c, E>(&mut self, e: E) -> Result<(), UnhandledError>whereE: sqlx::Executor<'c, Database = sqlx::Postgres>,@@ -413,11 +494,13 @@ mod test {use std::sync::Arc;use bytes::Bytes;+ use chrono::Utc;use httpmock::MockServer;use mockall::predicate;use posthog_symbol_data::write_symbol_data;use reqwest::Url;use sqlx::PgPool;+ use uuid::Uuid;use crate::{config::Config,@@ -532,6 +615,75 @@ mod test {map_mock.assert_hits(1);}+ #[sqlx::test(migrations = "./tests/test_migrations")]+ async fn test_dynamic_fetch_cleanup_when_existing_blob_wins_race(db: PgPool) {+ let server = MockServer::start();++ let mut config = Config::init_with_defaults().unwrap();+ config.object_storage_bucket = "test-bucket".to_string();+ config.ss_prefix = "test-prefix".to_string();++ let test_url = Url::parse(&server.url(CHUNK_PATH.to_string())).unwrap();+ let storage_ptr = "symbolsets/existing".to_string();++ let mut record = SymbolSetRecord {+ id: Uuid::now_v7(),+ team_id: 0,+ set_ref: test_url.to_string(),+ storage_ptr: Some(storage_ptr.clone()),+ failure_reason: None,+ created_at: Utc::now(),+ content_hash: Some("fake-hash".to_string()),+ last_used: Some(Utc::now()),+ };+ record.save(&db).await.unwrap();++ let mut client = MockS3Client::default();+ client+ .expect_put()+ .with(+ predicate::eq(config.object_storage_bucket.clone()),+ predicate::str::starts_with(config.ss_prefix.clone()),+ predicate::eq(Bytes::from(get_symbol_data_bytes())),+ )+ .returning(|_, _, _| Ok(()))+ .once();+ client+ .expect_delete()+ .with(+ predicate::eq(config.object_storage_bucket.clone()),+ predicate::str::starts_with(config.ss_prefix.clone()),+ )+ .returning(|_, _| Ok(()))+ .once();++ let smp = SourcemapProvider::new(&config);+ let saving_smp = Saving::new(+ smp,+ db.clone(),+ Arc::new(client),+ config.object_storage_bucket.clone(),+ config.ss_prefix.clone(),+ );++ saving_smp+ .save_data(+ 0,+ test_url.to_string(),+ Bytes::from(get_symbol_data_bytes()),+ )+ .await+ .unwrap();++ let record = SymbolSetRecord::load(&db, 0, test_url.as_ref())+ .await+ .unwrap()+ .unwrap();++ assert_eq!(record.storage_ptr.as_deref(), Some(storage_ptr.as_str()));+ assert!(record.failure_reason.is_none());+ }+#[sqlx::test(migrations = "./tests/test_migrations")]async fn test_symbol_set_404_handling(db: PgPool) {let server = MockServer::start();@@ -628,4 +780,57 @@ mod test {assert!(record.storage_ptr.is_none());}++ #[sqlx::test(migrations = "./tests/test_migrations")]+ async fn test_parse_failure_does_not_overwrite_existing_blob(db: PgPool) {+ let server = MockServer::start();++ let mut config = Config::init_with_defaults().unwrap();+ config.object_storage_bucket = "test-bucket".to_string();+ config.ss_prefix = "test-prefix".to_string();+ config.allow_internal_ips = true;++ let test_url = Url::parse(&server.url(CHUNK_PATH.to_string())).unwrap();+ let storage_ptr = "symbolsets/existing".to_string();++ let mut record = SymbolSetRecord {+ id: Uuid::now_v7(),+ team_id: 0,+ set_ref: test_url.to_string(),+ storage_ptr: Some(storage_ptr.clone()),+ failure_reason: None,+ created_at: Utc::now(),+ content_hash: Some("fake-hash".to_string()),+ last_used: Some(Utc::now()),+ };+ record.save(&db).await.unwrap();++ let mut client = MockS3Client::default();+ client+ .expect_get()+ .with(+ predicate::eq(config.object_storage_bucket.clone()),+ predicate::eq(storage_ptr.clone()),+ )+ .returning(|_, _| Ok(Some(Bytes::from_static(b"not a sourcemap"))));++ let smp = SourcemapProvider::new(&config);+ let saving_smp = Saving::new(+ smp,+ db.clone(),+ Arc::new(client),+ config.object_storage_bucket.clone(),+ config.ss_prefix.clone(),+ );++ saving_smp.lookup(0, test_url.clone()).await.unwrap_err();++ let record = SymbolSetRecord::load(&db, 0, test_url.as_ref())+ .await+ .unwrap()+ .unwrap();++ assert_eq!(record.storage_ptr.as_deref(), Some(storage_ptr.as_str()));+ assert!(record.failure_reason.is_none());+ }}diff --git a/rust/cymbal/src/test_utils.rs b/rust/cymbal/src/test_utils.rsindex 029cf1f081f1..6fa43d8a50ca 100644--- a/rust/cymbal/src/test_utils.rs+++ b/rust/cymbal/src/test_utils.rs@@ -20,6 +20,7 @@ mock! {impl BlobClient for S3Client {async fn get(&self, bucket: &str, key: &str) -> Result<Option<Bytes>, UnhandledError>;async fn put(&self, bucket: &str, key: &str, data: Bytes) -> Result<(), UnhandledError>;+ async fn delete(&self, bucket: &str, key: &str) -> Result<(), UnhandledError>;async fn ping_bucket(&self, bucket: &str) -> Result<(), UnhandledError>;}}diff --git a/rust/cymbal/tests/utils.rs b/rust/cymbal/tests/utils.rsindex e844fff08d86..5e45a319415f 100644--- a/rust/cymbal/tests/utils.rs+++ b/rust/cymbal/tests/utils.rs@@ -24,6 +24,7 @@ mock! {impl BlobClient for S3Client {async fn get(&self, bucket: &str, key: &str) -> Result<Option<Bytes>, UnhandledError>;async fn put(&self, bucket: &str, key: &str, data: Bytes) -> Result<(), UnhandledError>;+ async fn delete(&self, bucket: &str, key: &str) -> Result<(), UnhandledError>;async fn ping_bucket(&self, bucket: &str) -> Result<(), UnhandledError>;}}