: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): drop a remote url whose credential cannot be located (#98268)
Aleksander Błaszkiewicz484d0adc123f
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex d5a1cc24eb86..caff5c270de0 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -3491,6 +3491,7 @@ dependencies = ["tower 0.4.13","tracing","tracing-subscriber",+ "url","uuid","zip 4.6.1","zstd",diff --git a/rust/cymbal/Cargo.toml b/rust/cymbal/Cargo.tomlindex 53c31277ee59..1d8385337e17 100644--- a/rust/cymbal/Cargo.toml+++ b/rust/cymbal/Cargo.toml@@ -28,6 +28,7 @@ hogvm = { path = "../common/hogvm" }thiserror = { workspace = true }sqlx = { workspace = true }serde_json = { workspace = true }+url = { workspace = true }serde = { workspace = true }sourcemap = "9.0.0"symbolic = { version = "12.12", features = ["sourcemapcache", "debuginfo", "symcache", "demangle"] }diff --git a/rust/cymbal/src/core/types/frames/releases.rs b/rust/cymbal/src/core/types/frames/releases.rsindex a732758dfb2a..ffd0f93f3855 100644--- a/rust/cymbal/src/core/types/frames/releases.rs+++ b/rust/cymbal/src/core/types/frames/releases.rs@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};use serde_json::Value;use sha2::{Digest, Sha512};use sqlx::Executor;+use url::Url;use uuid::Uuid;use crate::symbolication::symbol_store::saving::truncate_ref;@@ -165,32 +166,88 @@ fn truncate_chars(value: &mut String, max_chars: usize) {fn sanitize_metadata_for_event(metadata: &Value) -> Value {let mut sanitized = metadata.clone();- if let Some(Value::String(remote_url)) = sanitized.pointer_mut("/git/remote_url") {- *remote_url = sanitize_remote_url(remote_url);+ let Some(Value::String(remote_url)) = sanitized.pointer("/git/remote_url") else {+ return sanitized;+ };++ match sanitize_remote_url(remote_url) {+ Some(cleaned) => {+ if let Some(Value::String(target)) = sanitized.pointer_mut("/git/remote_url") {+ *target = cleaned;+ }+ }+ // Dropping only the URL keeps branch, commit and repo name on the event.+ None => {+ if let Some(git) = sanitized.pointer_mut("/git").and_then(Value::as_object_mut) {+ git.remove("remote_url");+ }+ }}sanitized}-fn sanitize_remote_url(url: &str) -> String {- let sanitized_end = url.find(['?', '#']).unwrap_or(url.len());- let Some(scheme_end) = url[..sanitized_end].find("://") else {- return url[..sanitized_end].to_string();+/// Removes the userinfo component, the query, and the fragment from a git remote URL.+///+/// Returns `None` when a credential sits where no parser can isolate it, so the caller drops+/// the URL rather than store a secret.+fn sanitize_remote_url(url: &str) -> Option<String> {+ // `?token=` and `#access_token=` both carry secrets, and a git remote needs neither.+ let trimmed = match url.find(['?', '#']) {+ Some(index) => &url[..index],+ None => url,};- let authority_start = scheme_end + 3;- let authority_end = url[authority_start..sanitized_end]- .find('/')- .map_or(sanitized_end, |index| authority_start + index);- let authority = &url[authority_start..authority_end];- let Some(credentials_end) = authority.rfind('@') else {- return url[..sanitized_end].to_string();++ // `https://user:token?x@host/o/r.git` loses its `@` to the trim, and what remains is the+ // credential. Nothing tells that from a query that legitimately holds an `@`.+ if url.contains('@') && !trimmed.contains('@') {+ return None;+ }++ if !trimmed.contains("://") {+ // SSH carries no password, so the `git` in `git@host:owner/repo.git` is a fixed+ // username. Any other userinfo is not an SSH login and may be a token.+ let (authority, path) = trimmed.split_once(':').unwrap_or((trimmed, ""));+ let user = authority.split_once('@').map_or("", |(user, _)| user);+ return if (!user.is_empty() && user != "git") || path_holds_credential(path) {+ None+ } else {+ Some(trimmed.to_string())+ };+ }++ // Userinfo must percent-encode `/`, so `https://user:secret/@host/o/r.git` is malformed and+ // no scan can find where its authority ends. A parser that rejects it fails closed.+ let Ok(mut parsed) = Url::parse(trimmed) else {+ return if trimmed.contains('@') {+ None+ } else {+ Some(trimmed.to_string())+ };};- format!(- "{}{}{}",- &url[..authority_start],- &authority[credentials_end + 1..],- &url[authority_end..sanitized_end]- )+ // `https://host/${TOKEN}@host/o/r.git` is a CI script interpolating one segment too late.+ // The authority parses clean, so userinfo stripping never sees the token.+ if path_holds_credential(parsed.path()) {+ return None;+ }++ // Returning the input untouched keeps the parser from reshaping a URL holding no credential.+ if parsed.username().is_empty() && parsed.password().is_none() {+ return Some(trimmed.to_string());+ }++ parsed.set_username("").ok()?;+ parsed.set_password(None).ok()?;+ Some(parsed.to_string())+}++/// An `@` opening a segment is an npm scope (`/@scope/package`), not a credential.+fn path_holds_credential(path: &str) -> bool {+ path.split('/').any(|segment| {+ segment+ .split_once('@')+ .is_some_and(|(before, _)| !before.is_empty())+ })}/// Reconstruct the release `hash_id` the CLI wrote for a mobile build, from the app metadata the@@ -328,35 +385,63 @@ mod tests {#[test]fn event_remote_urls_drop_credentials_query_and_fragment() {- let cases = [+ // `None` means the URL cannot be cleaned, so the key is dropped from the event.+ let cases: [(&str, Option<&str>); 12] = [("https://user:[email protected]/example/repo.git?token=query#access_token=fragment",- "https://github.com/example/repo.git",+ Some("https://github.com/example/repo.git"),),("https://github.com/example/repo.git#access_token=fragment",- "https://github.com/example/repo.git",+ Some("https://github.com/example/repo.git"),),("https://github.com/example/repo.git",- "https://github.com/example/repo.git",+ Some("https://github.com/example/repo.git"),),("[email protected]:example/repo.git",- "[email protected]:example/repo.git",+ Some("[email protected]:example/repo.git"),),("[email protected]:example/repo.git?token=query#access_token=fragment",- "[email protected]:example/repo.git",+ Some("[email protected]:example/repo.git"),+ ),+ (+ "https://github.com/[email protected]/example/repo.git",+ None,+ ),+ ("[email protected]:ghs_tokenvalue@example/repo.git", None),+ // SSH has no password slot, so a non-`git` userinfo is not a login.+ ("[email protected]:example/repo.git", None),+ // An unencoded `/` in the password moves the `@` to the head of a path segment,+ // where it would otherwise read as a scope.+ ("https://user:secret/@github.com/example/repo.git", None),+ ("https://user:sec/[email protected]/example/repo.git", None),+ ("https://user:[email protected]/example/repo.git", None),+ (+ "https://github.com/example/@scope/package.git",+ Some("https://github.com/example/@scope/package.git"),),];for (remote_url, expected) in cases {let info = serde_json::to_value(- record(Some(json!({"git": {"remote_url": remote_url}}))).to_info(),+ record(Some(+ json!({"git": {"remote_url": remote_url, "branch": "main"}}),+ ))+ .to_info(),).unwrap();- assert_eq!(info["metadata"]["git"]["remote_url"], expected);+ let git = &info["metadata"]["git"];+ match expected {+ Some(value) => assert_eq!(git["remote_url"], value, "case: {remote_url}"),+ None => assert!(+ git.get("remote_url").is_none(),+ "case: {remote_url} should have been dropped, got {git:?}"+ ),+ }+ assert_eq!(git["branch"], "main", "case: {remote_url}");}}