: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(data-warehouse): support the Gladly sandbox domain (#78038)
jake sciottod34321a7340d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/gladly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/gladly.pyindex 733cfcb41965..69dae5891093 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/gladly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/gladly.py@@ -1,6 +1,8 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@@ -9,3 +11,4 @@ class GladlySourceConfig(config.Config):organization: stragent_email: strapi_token: str+ domain: Literal["gladly.com", "gladly.qa"] = config.value(default="gladly.com")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.pyindex 012a2038e909..e715a376971e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.py@@ -35,6 +35,13 @@ REPORT_ROW_WARNING_THRESHOLD = 90_000# windows are paced instead of riding the 429 backoff.REPORT_REQUEST_INTERVAL_SECONDS = 6.0+# Gladly serves production on gladly.com and the testing sandbox on gladly.qa. The+# config field is typed as a Literal, but nothing validates Literal membership at+# runtime, so the domain is checked against this tuple before it reaches a URL. An+# unchecked value would send the Basic-auth credentials to an arbitrary host.+ALLOWED_DOMAINS = ("gladly.com", "gladly.qa")+DEFAULT_DOMAIN = "gladly.com"+class GladlyRetryableError(Exception):pass@@ -72,12 +79,19 @@ def _clean_organization(organization: str) -> str:return org-def _host(organization: str) -> str:- return f"{_clean_organization(organization)}.gladly.com"+def _clean_domain(domain: str) -> str:+ value = domain.strip().lower()+ if value not in ALLOWED_DOMAINS:+ raise ValueError(f"Invalid Gladly domain. Choose one of: {', '.join(ALLOWED_DOMAINS)}.")+ return value+++def _host(organization: str, domain: str = DEFAULT_DOMAIN) -> str:+ return f"{_clean_organization(organization)}.{_clean_domain(domain)}"-def _base_url(organization: str) -> str:- return f"https://{_host(organization)}/api/v1"+def _base_url(organization: str, domain: str = DEFAULT_DOMAIN) -> str:+ return f"https://{_host(organization, domain)}/api/v1"def _format_timestamp(value: Any) -> str:@@ -145,7 +159,9 @@ def _report_start_date(return min(start, today)-def validate_credentials(organization: str, agent_email: str, api_token: str) -> tuple[bool, str | None]:+def validate_credentials(+ organization: str, agent_email: str, api_token: str, domain: str = DEFAULT_DOMAIN+) -> tuple[bool, str | None]:"""Confirm the credentials are valid with a cheap agents probe.A wrong subdomain, an agent missing the API User permission, and a bad token each@@ -154,8 +170,8 @@ def validate_credentials(organization: str, agent_email: str, api_token: str) ->unreachable host or a Gladly outage behind a credentials error."""try:- base_url = _base_url(organization)- host = _host(organization)+ base_url = _base_url(organization, domain)+ host = _host(organization, domain)except ValueError as e:return False, str(e)@@ -192,10 +208,11 @@ def get_rows(resumable_source_manager: ResumableSourceManager[GladlyResumeConfig],should_use_incremental_field: bool = False,db_incremental_field_last_value: Any = None,+ domain: str = DEFAULT_DOMAIN,) -> Iterator[list[dict[str, Any]]]:config = GLADLY_ENDPOINTS[endpoint]session = _get_session(agent_email, api_token)- base_url = _base_url(organization)+ base_url = _base_url(organization, domain)if config.report_metric_set is not None:yield from _report_rows(@@ -402,6 +419,7 @@ def gladly_source(resumable_source_manager: ResumableSourceManager[GladlyResumeConfig],should_use_incremental_field: bool = False,db_incremental_field_last_value: Optional[Any] = None,+ domain: str = DEFAULT_DOMAIN,) -> SourceResponse:config = GLADLY_ENDPOINTS[endpoint]@@ -416,6 +434,7 @@ def gladly_source(resumable_source_manager=resumable_source_manager,should_use_incremental_field=should_use_incremental_field,db_incremental_field_last_value=db_incremental_field_last_value,+ domain=domain,),primary_keys=[config.primary_key],partition_count=1,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.pyindex 2359a9fb0081..f1ab2ab7ae01 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.py@@ -7,6 +7,8 @@ from posthog.schema import (SourceConfig,SourceFieldInputConfig,SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource@@ -49,9 +51,9 @@ class GladlySource(ResumableSource[GladlySourceConfig, GladlyResumeConfig]):@propertydef connection_host_fields(self) -> list[str]:- # `organization` determines the host the stored token is sent to;- # retargeting it must re-require the token.- return ["organization"]+ # `organization` and `domain` together determine the host the stored token is+ # sent to; retargeting either must re-require the token.+ return ["organization", "domain"]def get_canonical_descriptions(self) -> CanonicalDescriptions:from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.canonical_descriptions import (@@ -74,7 +76,7 @@ class GladlySource(ResumableSource[GladlySourceConfig, GladlyResumeConfig]):label="Gladly",caption="""Connect your Gladly account to pull your customer service data into the PostHog Data warehouse.-Your organization is the part of your Gladly URL before `.gladly.com`. For `myorg.gladly.com` enter `myorg`, and for `myorg.us-1.gladly.com` enter `myorg.us-1`. The API token must belong to an agent with the API User permission (Settings > API Tokens). Data comes from Gladly's scheduled export jobs, which retain files for 14 days. History older than that requires asking Gladly support to regenerate exports. The conversation and contact timestamps tables come from Gladly's reports instead and reach back 90 days on their first sync.""",+Your organization is the part of your Gladly URL before `.gladly.com`. For `myorg.gladly.com` enter `myorg`, and for `myorg.us-1.gladly.com` enter `myorg.us-1`. The API token must belong to an agent with the API User permission (Settings > API Tokens). Leave the domain on Production unless you are connecting a Gladly sandbox, which is served on `gladly.qa`. Data comes from Gladly's scheduled export jobs, which retain files for 14 days. History older than that requires asking Gladly support to regenerate exports. The conversation and contact timestamps tables come from Gladly's reports instead and reach back 90 days on their first sync.""",iconPath="/static/services/gladly.png",docsUrl="https://posthog.com/docs/cdp/sources/gladly",releaseStatus=ReleaseStatus.ALPHA,@@ -105,6 +107,16 @@ Your organization is the part of your Gladly URL before `.gladly.com`. For `myorplaceholder="",secret=True,),+ SourceFieldSelectConfig(+ name="domain",+ label="Gladly domain",+ required=True,+ defaultValue="gladly.com",+ options=[+ SourceFieldSelectConfigOption(label="Production (gladly.com)", value="gladly.com"),+ SourceFieldSelectConfigOption(label="Sandbox (gladly.qa)", value="gladly.qa"),+ ],+ ),],),)@@ -136,7 +148,7 @@ Your organization is the part of your Gladly URL before `.gladly.com`. For `myorschema_name: Optional[str] = None,api_version: str | None = None,) -> tuple[bool, str | None]:- return validate_gladly_credentials(config.organization, config.agent_email, config.api_token)+ return validate_gladly_credentials(config.organization, config.agent_email, config.api_token, config.domain)def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GladlyResumeConfig]:return ResumableSourceManager[GladlyResumeConfig](inputs, GladlyResumeConfig)@@ -158,4 +170,5 @@ Your organization is the part of your Gladly URL before `.gladly.com`. For `myordb_incremental_field_last_value=inputs.db_incremental_field_last_valueif inputs.should_use_incremental_fieldelse None,+ domain=config.domain,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.pyindex 19b11f113471..7612d932864e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.glaGladlyResumeConfig,GladlyRetryableError,_base_url,+ _clean_domain,_clean_organization,_normalize_report_column,get_rows,@@ -95,8 +96,34 @@ class TestCleanOrganization:with pytest.raises(ValueError):_clean_organization(value)- def test_base_url(self):- assert _base_url("myorg") == "https://myorg.gladly.com/api/v1"+ @pytest.mark.parametrize(+ "domain, expected",+ [+ (None, "https://myorg.gladly.com/api/v1"),+ ("gladly.com", "https://myorg.gladly.com/api/v1"),+ ("gladly.qa", "https://myorg.gladly.qa/api/v1"),+ ],+ )+ def test_base_url(self, domain, expected):+ assert (_base_url("myorg") if domain is None else _base_url("myorg", domain)) == expected+++class TestCleanDomain:+ @pytest.mark.parametrize(+ "value, expected",+ [+ ("gladly.com", "gladly.com"),+ ("gladly.qa", "gladly.qa"),+ (" GLADLY.QA ", "gladly.qa"),+ ],+ )+ def test_allowed_domains(self, value, expected):+ assert _clean_domain(value) == expected++ @pytest.mark.parametrize("value", ["", "evil.com", "gladly.com.evil.com", "gladly.qa.evil.com", "gladly.dev"])+ def test_domains_outside_the_allowlist_raise(self, value):+ with pytest.raises(ValueError):+ _clean_domain(value)class TestValidateCredentials:@@ -143,6 +170,30 @@ class TestValidateCredentials:assert "Invalid Gladly organization" in (message or "")mock_session.assert_not_called()+ @pytest.mark.parametrize(+ "domain, expected_url",+ [+ ("gladly.com", "https://myorg.gladly.com/api/v1/agents"),+ ("gladly.qa", "https://myorg.gladly.qa/api/v1/agents"),+ ],+ )+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_probe_targets_the_selected_domain(self, mock_session, domain, expected_url):+ response = mock.MagicMock()+ response.status_code = 200+ mock_session.return_value.get.return_value = response++ assert validate_credentials("myorg", "[email protected]", "token", domain) == (True, None)+ assert mock_session.return_value.get.call_args.args[0] == expected_url++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_domain_outside_the_allowlist_is_never_probed(self, mock_session):+ is_valid, message = validate_credentials("myorg", "[email protected]", "token", "evil.com")++ assert is_valid is False+ assert "Invalid Gladly domain" in (message or "")+ mock_session.assert_not_called()+@mock.patch(f"{_MODULE}.make_tracked_session")def test_session_uses_basic_auth(self, mock_session):response = mock.MagicMock()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.pyindex 870d647b5966..29929f18f7aa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.py@@ -30,7 +30,7 @@ class TestGladlySource:assert config.iconPath == "/static/services/gladly.png"field_names = [f.name for f in config.fields]- assert field_names == ["organization", "agent_email", "api_token"]+ assert field_names == ["organization", "agent_email", "api_token", "domain"]def test_api_token_field_is_secret_password(self):config = self.source.get_source_config@@ -40,8 +40,8 @@ class TestGladlySource:assert token_field.required is Truedef test_connection_host_fields_cover_organization(self):- # The org subdomain decides where the stored token gets sent.- assert self.source.connection_host_fields == ["organization"]+ # The org subdomain and the domain together decide where the stored token gets sent.+ assert self.source.connection_host_fields == ["organization", "domain"]@pytest.mark.parametrize("observed_error",@@ -108,7 +108,7 @@ class TestGladlySource:mock_validate.return_value = mock_returnassert self.source.validate_credentials(self.config, self.team_id) == mock_return- mock_validate.assert_called_once_with("myorg", "[email protected]", "token")+ mock_validate.assert_called_once_with("myorg", "[email protected]", "token", "gladly.com")def test_get_resumable_source_manager_binds_resume_config(self):inputs = mock.MagicMock()@@ -117,18 +117,21 @@ class TestGladlySource:assert isinstance(manager, ResumableSourceManager)assert manager._data_class is GladlyResumeConfig+ @pytest.mark.parametrize("domain", ["gladly.com", "gladly.qa"])@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.gladly.source.gladly_source")- def test_source_for_pipeline_plumbs_arguments(self, mock_gladly_source):+ def test_source_for_pipeline_plumbs_arguments(self, mock_gladly_source, domain):inputs = mock.MagicMock()inputs.schema_name = "customers"inputs.should_use_incremental_field = Trueinputs.db_incremental_field_last_value = "2024-01-02T03:04:05.000Z"manager = mock.MagicMock()+ config = GladlySourceConfig(organization="myorg", agent_email="[email protected]", api_token="token", domain=domain)- self.source.source_for_pipeline(self.config, manager, inputs)+ self.source.source_for_pipeline(config, manager, inputs)mock_gladly_source.assert_called_once()kwargs = mock_gladly_source.call_args.kwargs+ assert kwargs["domain"] == domainassert kwargs["organization"] == "myorg"assert kwargs["agent_email"] == "[email protected]"assert kwargs["api_token"] == "token"