: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(sentry): normalize a pasted org URL into the organization slug (#76533)
Tom Owersdeb4b282aace
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.pyindex 2c7ee8e8bf7f..64ff9d779cbf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py@@ -3,7 +3,7 @@ import dataclassesfrom collections.abc import Callable, Iterable, Iteratorfrom datetime import UTC, datetime, timedeltafrom typing import Any, Optional, cast-from urllib.parse import quote, urljoin+from urllib.parse import quote, urljoin, urlparseimport structlogfrom dateutil import parser as dateutil_parser@@ -79,6 +79,45 @@ class SentryResumeConfig:values_next_url: Optional[str] = None+# Sentry exposes an org URL as `https://<org>.sentry.io/` in its UI and as+# `https://sentry.io/organizations/<org>/...` in deep links, so users routinely paste one of+# those into the slug field instead of the bare slug.+_SENTRY_NON_ORG_SUBDOMAINS = {"www", "us", "de", "eu", "app"}+++def _normalize_organization_slug(organization_slug: str) -> str:+ """Pull the org slug out of a pasted Sentry URL.++ A valid Sentry org slug is lowercase alphanumeric plus hyphens, so any `/`, `:`, or `.` in the+ value means it's a URL or host, not a slug. Extract the slug from the two shapes Sentry uses and+ leave a bare slug untouched. Because a real slug can never contain those characters, an input we+ rewrite here would have failed the credential check anyway, so a wrong guess can only produce the+ same failure with a clearer target, never hijack a valid slug.+ """+ slug = organization_slug.strip()+ if not any(char in slug for char in "/:."):+ return slug++ parsed = urlparse(slug if "//" in slug else f"https://{slug}")+ segments = [segment for segment in parsed.path.split("/") if segment]++ if "organizations" in segments:+ index = segments.index("organizations")+ if index + 1 < len(segments):+ return segments[index + 1]++ host = (parsed.hostname or "").lower()+ if host.endswith(".sentry.io"):+ subdomain = host.removesuffix(".sentry.io")+ if subdomain and subdomain not in _SENTRY_NON_ORG_SUBDOMAINS:+ return subdomain++ # Couldn't confidently identify a slug (e.g. a bare `sentry.io` or an `/organizations/` path+ # with no slug after it), so leave the value untouched. The credential check then reports the+ # exact thing the user typed rather than a misleading guess like the literal "organizations".+ return slug++def _normalize_api_base_url(api_base_url: str | None) -> str:return (api_base_url or DEFAULT_SENTRY_API_BASE_URL).rstrip("/")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/source.pyindex 115a5e1c4e6d..45574aef671f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/source.py@@ -22,6 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sentry import SentrySourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry import (SentryResumeConfig,+ _normalize_organization_slug,sentry_source,validate_credentials as validate_sentry_credentials,)@@ -47,6 +48,15 @@ class SentrySource(ResumableSource[SentrySourceConfig, SentryResumeConfig]):def source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SENTRY+ def parse_config(self, job_inputs: dict) -> SentrySourceConfig:+ # Normalize before building the config so both the credential check and the stored+ # job_inputs use the extracted slug. Normalizing only in validate_credentials would let a+ # pasted URL pass validation but persist as the slug, breaking every later sync.+ organization_slug = job_inputs.get("organization_slug")+ if isinstance(organization_slug, str):+ job_inputs = {**job_inputs, "organization_slug": _normalize_organization_slug(organization_slug)}+ return self._config_class.from_dict(job_inputs)+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/tests/test_sentry.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/tests/test_sentry.pyindex 608c61be7343..884c799e3743 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/tests/test_sentry.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/tests/test_sentry.py@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.sentry.senSentryResumeConfig,_custom_endpoint_rows,_normalize_api_base_url,+ _normalize_organization_slug,_parse_next_link,_retention_bounded_start_param,_retry_wait_seconds,@@ -95,6 +96,22 @@ class TestSentryTransport:assert _normalize_api_base_url(None) == "https://sentry.io"assert _normalize_api_base_url("https://us.sentry.io/") == "https://us.sentry.io"+ @parameterized.expand(+ [+ ("bare_slug", "acme", "acme"),+ ("bare_slug_trims_whitespace", " acme ", "acme"),+ ("org_subdomain_url", "https://acme.sentry.io/", "acme"),+ ("org_subdomain_url_no_scheme", "acme.sentry.io", "acme"),+ ("org_subdomain_with_path", "https://acme.sentry.io/issues/", "acme"),+ ("organizations_deep_link", "https://sentry.io/organizations/acme/issues/", "acme"),+ ("organizations_deep_link_no_scheme", "sentry.io/organizations/acme", "acme"),+ # No slug to extract: return the input as-is rather than guessing the literal "organizations".+ ("organizations_path_without_slug", "https://sentry.io/organizations/", "https://sentry.io/organizations/"),+ ]+ )+ def test_normalize_organization_slug_extracts_slug(self, _name: str, value: str, expected: str) -> None:+ assert _normalize_organization_slug(value) == expected+def test_start_param_for_sentry_formats_datetime(self) -> None:value = datetime(2025, 1, 1, 10, 30, 0, tzinfo=UTC)assert _start_param_for_sentry(value) == "2025-01-01T10:30:00"@@ -329,6 +346,11 @@ class TestSentrySourceValidation:api_base_url="https://sentry.io",)+ def test_parse_config_normalizes_pasted_org_url(self) -> None:+ config = SentrySource().parse_config({"auth_token": "token", "organization_slug": "https://acme.sentry.io/"})++ assert config.organization_slug == "acme"+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry.rest_api_resource")def test_sentry_source_builds_response(self, mock_rest_api_resource) -> None:mock_resource = Mock()