Skip to content

: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.

fix(warehouse-sources): keep scope-gated HubSpot tables in discovery (#98635)

Daniel RCcffe65e2279e
diff --git a/posthog/models/test/integration/test_oauth.py b/posthog/models/test/integration/test_oauth.py
index 640849a30855..94757babc697 100644
--- a/posthog/models/test/integration/test_oauth.py
+++ b/posthog/models/test/integration/test_oauth.py
@@ -128,6 +128,17 @@ class TestOauthIntegrationModel(BaseTest):
assert "code_challenge" not in url
assert cache.get("oauth_pkce_verifier/no_pkce_state_token") is None
+ def test_hubspot_authorize_url_requests_plan_gated_read_scopes_as_optional(self):
+ # A plan-gated scope in the mandatory `scope` fails the whole authorization for a portal
+ # that cannot grant it. Dropping it from `optional_scope` is just as bad: the connection
+ # authorizes without the scope and the tables it covers 403 on every sync.
+ with self.settings(**self.mock_settings):
+ url = OauthIntegration.authorize_url("hubspot", token="state_token", next="/projects/test")
+ params = {k: v[0] for k, v in parse_qs(url.partition("?")[2]).items()}
+
+ assert "crm.objects.leads.read" in params["optional_scope"].split(" ")
+ assert "crm.objects.leads.read" not in params["scope"].split(" ")
+
def test_authorize_url_with_additional_authorize_params(self):
with self.settings(**self.mock_settings):
url = OauthIntegration.authorize_url("google-ads", token="state_token", next="/projects/test")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/source.py
index 71f7ee1f5eb4..b4663a644031 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/source.py
@@ -193,13 +193,8 @@ class HubspotSource(ResumableSource[HubspotSourceConfig | HubspotSourceOldConfig
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- unreadable = self._endpoints_missing_scopes(config, team_id)
-
schemas = []
for endpoint in HUBSPOT_ENDPOINTS:
- if endpoint in unreadable:
- continue
-
metadata_config = HUBSPOT_METADATA_ENDPOINT_CONFIGS.get(endpoint)
if metadata_config is not None:
# Lookup tables have no server-side timestamp filter, so they are full refresh only.
@@ -232,35 +227,52 @@ class HubspotSource(ResumableSource[HubspotSourceConfig | HubspotSourceOldConfig
return schemas
- def _endpoints_missing_scopes(
- self, config: HubspotSourceConfig | HubspotSourceOldConfig, team_id: int
- ) -> frozenset[str]:
- """Endpoints this connection provably cannot read, for want of an optional scope.
+ def get_endpoint_permissions(
+ self,
+ config: HubspotSourceConfig | HubspotSourceOldConfig,
+ team_id: int,
+ endpoints: list[str],
+ api_version: str | None = None,
+ ) -> dict[str, str | None]:
+ missing = self._missing_scopes(config, team_id)
+ reasons: dict[str, str | None] = {}
+ for endpoint in endpoints:
+ scope = missing.get(endpoint)
+ reasons[endpoint] = (
+ f"Reconnect your HubSpot account to grant the {scope} permission. Not every HubSpot plan includes it."
+ if scope is not None
+ else None
+ )
+ return reasons
+
+ def _missing_scopes(self, config: HubspotSourceConfig | HubspotSourceOldConfig, team_id: int) -> dict[str, str]:
+ """Optional scopes this connection lacks, keyed by the endpoint that needs one.
- Keeping them out of discovery means nobody can select a table whose every sync would 403,
- and an already-selected one gets turned off by the next discovery run.
+ Discovery still lists these endpoints. A table that the picker never shows leaves the user
+ with nothing to reconnect for, so the gap is reported next to the table instead.
"""
if not SCOPE_GATED_OBJECTS or not isinstance(config, HubspotSourceConfig):
- return frozenset()
+ return {}
try:
integration = self.get_oauth_integration(config.hubspot_integration_id, team_id)
except ValueError as e:
- # A missing or deleted integration is permanent, but discovery stays best-effort
+ # A missing or deleted integration is permanent, but the scope check stays best-effort
# because the sync path already surfaces it with an actionable message.
- logger.warning(f"Hubspot scope gating skipped, integration lookup failed: {e}", team_id=team_id)
- return frozenset()
+ logger.warning(f"Hubspot scope check skipped, integration lookup failed: {e}", team_id=team_id)
+ return {}
except Exception:
- # Dropping tables on a transient lookup failure would churn schema rows, so gating
- # fails open. Log it so a gating no-op is distinguishable from unknown scopes.
- logger.exception("Hubspot scope gating skipped, integration lookup failed", team_id=team_id)
- return frozenset()
-
- return frozenset(
- endpoint
- for endpoint in SCOPE_GATED_OBJECTS
- if missing_scope_for_endpoint(endpoint, integration.config) is not None
- )
+ # A transient lookup failure must not mark a readable table as unreadable, so the check
+ # fails open. Log it so a no-op check is distinguishable from complete scopes.
+ logger.exception("Hubspot scope check skipped, integration lookup failed", team_id=team_id)
+ return {}
+
+ missing = {}
+ for endpoint in SCOPE_GATED_OBJECTS:
+ scope = missing_scope_for_endpoint(endpoint, integration.config)
+ if scope is not None:
+ missing[endpoint] = scope
+ return missing
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HubspotResumeConfig]:
return ResumableSourceManager[HubspotResumeConfig](inputs, HubspotResumeConfig)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_scopes.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_scopes.py
index 8cbd0883cc48..6d8c7da37075 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_scopes.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_scopes.py
@@ -118,20 +118,25 @@ class TestScopeGatingInSource:
@parameterized.expand(
[
- ("granted", {"scopes": [LEADS_SCOPE]}, True),
- ("not_granted", {"scopes": ["tickets"]}, False),
- ("unknown", {}, True),
+ ("granted", {"scopes": [LEADS_SCOPE]}, None),
+ ("not_granted", {"scopes": ["tickets"]}, LEADS_SCOPE),
+ ("unknown", {}, None),
]
)
- def test_leads_offered_only_when_the_scope_is_not_provably_missing(
- self, _name: str, integration_config: dict[str, Any], expected: bool
+ def test_leads_is_always_offered_and_names_the_scope_it_needs(
+ self, _name: str, integration_config: dict[str, Any], expected_scope: str | None
) -> None:
source = HubspotSource()
with patch.object(source, "get_oauth_integration", return_value=_integration(integration_config)):
names = {schema.name for schema in source.get_schemas(self._config(), team_id=1)}
-
- assert ("leads" in names) is expected
- assert "deals" in names
+ permissions = source.get_endpoint_permissions(self._config(), 1, ["leads", "deals"])
+
+ assert {"leads", "deals"} <= names
+ assert permissions["deals"] is None
+ if expected_scope is None:
+ assert permissions["leads"] is None
+ else:
+ assert expected_scope in (permissions["leads"] or "")
def test_sync_fails_with_an_actionable_error_when_the_scope_is_missing(self) -> None:
source = HubspotSource()