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.

feat(data-warehouse): move legacy hubspot tokens into integration rows (#130026)

Tom Owerse9c6a81dbd65
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.md
index 71594b6c26c8..2f2391b8e874 100644
--- a/.agents/skills/implementing-warehouse-sources/SKILL.md
+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md
@@ -491,6 +491,14 @@ A source's OAuth field (`SourceFieldOauthConfig`, a `*_integration_id` input) ca
- The default walks the form (`sources/common/oauth_pointers.py`). It reads only the shape that `serialize_config` writes: a select as a mapping with `selection`, a switch group as a mapping with `enabled`. Any other shape (a flat legacy key, a select stored as a string) raises `OAuthPointerShapeError`. Callers then leave the source alone. They never guess.
- Override `in_use_oauth_slot` and `oauth_pointer_paths` on your source class only for a pointer that no form field declares. Slack does this for its legacy `slack_integration_id`, which a pasted `slack_access_token` overrides.
+#### Backfill outcomes for legacy OAuth tokens
+
+`backfill_warehouse_source_credentials` moves legacy OAuth tokens that sit in `job_inputs` into an OAuth `Integration` row.
+A source opts in with two hooks on its class: `has_legacy_oauth_tokens(job_inputs)` (no network) and `adopt_legacy_oauth(job_inputs)` (can call the provider). HubSpot is the only source that uses them.
+
+- `hubspot_legacy_adopted`: the source has `hubspot_secret_key` and `hubspot_refresh_token` and no `hubspot_integration_id`. With `--execute`, the command exchanges the refresh token, reads the hub id from HubSpot, and reuses the `hubspot` row of the team for that hub id or creates one. It then sets `hubspot_integration_id` and the column, and removes the two legacy keys. Preview only counts. `reconcile_warehouse_source_credentials --verify` reports it as `legacy_oauth_tokens_in_job_inputs`.
+- `skipped_legacy_token_unusable`: HubSpot rejected the token, returned no hub id, failed after the retries, or the inputs changed during the run. The command writes nothing. A later run tries again.
+
## Implementing `source_for_pipeline`
Return a `SourceResponse` directly. **Do not** use `dlt_source_to_source_response` for new sources — DLT is being removed.
diff --git a/products/warehouse_sources/backend/logic/source_credentials_sync.py b/products/warehouse_sources/backend/logic/source_credentials_sync.py
index 629a2ece9061..126f3c9c2644 100644
--- a/products/warehouse_sources/backend/logic/source_credentials_sync.py
+++ b/products/warehouse_sources/backend/logic/source_credentials_sync.py
@@ -7,6 +7,9 @@ The backfill fills each source's `credentials_integration_id` column with the on
row, so a run can be repeated. The backfill never merges two sources into one row, because that would put
the secrets of both under one edit point.
- An OAuth source: the column gets the in-use `*_integration_id` pointer of its stored `job_inputs`.
+- A legacy HubSpot source: execution exchanges its tokens and creates or reuses a HubSpot OAuth row.
+ It removes the legacy tokens and saves the pointer and column together. Preview makes no network calls.
+ Unusable grants are skipped so a later run can retry.
Old rows can hold shapes that the OAuth walk does not read (a flat legacy key, a select stored as a string).
The backfill logs and skips them. It never guesses which pointer is in use.
@@ -18,7 +21,7 @@ integrations list.
from collections import Counter
from collections.abc import Callable, Iterable, Mapping, Sequence
-from typing import Any
+from typing import TYPE_CHECKING, Any, cast
from uuid import UUID
from django.db import transaction
@@ -26,7 +29,7 @@ from django.db import transaction
import structlog
from posthog.dataclasses import frozen
-from posthog.integrations import IntegrationManager, IntegrationReference
+from posthog.integrations import IntegrationConflict, IntegrationManager, IntegrationReference
from products.warehouse_sources.backend.facade.contracts import SharedCredentialsError, UnreadableSourceInputsError
from products.warehouse_sources.backend.logic.credential_auth_types import has_typed_in_credentials
@@ -43,6 +46,9 @@ from products.warehouse_sources.backend.logic.source_credentials_rollout import
)
from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.legacy_oauth import (
+ LegacyOAuthGrantUnusable,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.oauth_pointers import (
OAuthPointerShapeError,
PointerPath,
@@ -50,6 +56,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.oau
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+if TYPE_CHECKING:
+ from posthog.integrations.accessors import OAuthAccessor
+
logger = structlog.get_logger(__name__)
CREATED = "created"
@@ -57,6 +66,8 @@ UPDATED = "updated"
RECREATED = "recreated"
UNCHANGED = "unchanged"
OAUTH_LINKED = "oauth_linked"
+HUBSPOT_LEGACY_ADOPTED = "hubspot_legacy_adopted"
+SKIPPED_LEGACY_UNUSABLE = "skipped_legacy_token_unusable"
SKIPPED_SHAPE = "skipped_unreadable_shape"
SKIPPED_NO_ROW = "skipped_no_row"
SKIPPED_SHARED = "skipped_shared"
@@ -72,6 +83,7 @@ NOT_BACKFILLED = frozenset(
UPDATED,
RECREATED,
OAUTH_LINKED,
+ HUBSPOT_LEGACY_ADOPTED,
SKIPPED_SHARED,
SKIPPED_UNREADABLE,
SKIPPED_SHAPE,
@@ -218,11 +230,11 @@ def _process_batch(batch: Iterable[ExternalDataSource], execute: bool, counts: B
except ValueError:
counts[(source_type, SKIPPED_UNKNOWN_TYPE)] += 1
continue
- if plan == OAUTH_LINKED:
- _run(source, execute, plan, counts)
- continue
if isinstance(plan, str):
- counts[(source_type, plan)] += 1
+ if plan in (OAUTH_LINKED, HUBSPOT_LEGACY_ADOPTED):
+ _run(source, execute, plan, counts)
+ else:
+ counts[(source_type, plan)] += 1
continue
planned.append((source, plan))
if not planned:
@@ -244,9 +256,10 @@ def _process_batch(batch: Iterable[ExternalDataSource], execute: bool, counts: B
def _plan(source: ExternalDataSource) -> dict[str, Any] | str:
- """The connection fields that the row of a source with typed-in credentials must hold, or the outcome of
- a source that needs no row write (an OAuth source, a source without connection fields)."""
+ """Return the stored typed-in fields or the planned outcome, without network calls or writes."""
inputs = SourceInputsStore.load_stored(source)
+ if _has_legacy_oauth_tokens(source, inputs):
+ return HUBSPOT_LEGACY_ADOPTED
slot = in_use_oauth_slot(str(source.source_type), inputs)
if slot is not None:
return _oauth_outcome(source, inputs, slot)
@@ -269,7 +282,7 @@ def _oauth_outcome(source: ExternalDataSource, inputs: Mapping[str, Any], slot:
def _run(source: ExternalDataSource, execute: bool, outcome: str, counts: BackfillCounts) -> None:
if execute:
try:
- outcome = _sync_source(source)
+ outcome = _adopt_legacy_oauth(source) if outcome == HUBSPOT_LEGACY_ADOPTED else _sync_source(source)
except OAuthPointerShapeError:
_log_shape(source)
outcome = SKIPPED_SHAPE
@@ -298,6 +311,68 @@ def _stored_connection_fields(source: ExternalDataSource, inputs: Mapping[str, A
return recovered
+def _has_legacy_oauth_tokens(source: ExternalDataSource, inputs: Mapping[str, Any]) -> bool:
+ # The registry loads every source, so keep it off this module's import path.
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import ( # noqa: PLC0415 — heavy import
+ SourceRegistry,
+ )
+
+ return SourceRegistry.get_source(ExternalDataSourceType(source.source_type)).has_legacy_oauth_tokens(inputs)
+
+
+def _adopt_legacy_oauth(source: ExternalDataSource) -> str:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import ( # noqa: PLC0415 - heavy registry import
+ SourceRegistry,
+ )
+
+ inputs = SourceInputsStore.load_stored(source)
+ source_class = SourceRegistry.get_source(ExternalDataSourceType(source.source_type))
+ try:
+ grant = source_class.adopt_legacy_oauth(inputs)
+ except LegacyOAuthGrantUnusable:
+ logger.warning("warehouse_source_credentials.backfill_legacy_token_unusable", source_id=str(source.id))
+ return SKIPPED_LEGACY_UNUSABLE
+ if grant is None:
+ return _sync_source(source)
+
+ with transaction.atomic():
+ fresh = (
+ ExternalDataSource.objects.select_related(None)
+ .select_for_update(of=("self",))
+ .filter(pk=source.pk, team_id=source.team_id)
+ .exclude(deleted=True)
+ .first()
+ )
+ if fresh is None:
+ return SKIPPED_DELETED
+ fresh_inputs = SourceInputsStore.load_stored(fresh)
+ if grant.pointer_key in fresh_inputs:
+ return _sync_source(fresh)
+ if fresh_inputs.get("hubspot_refresh_token") != grant.refresh_token:
+ return SKIPPED_LEGACY_UNUSABLE
+
+ oauth = cast("OAuthAccessor", getattr(IntegrationManager, grant.kind.replace("-", "_")).oauth)
+ row = oauth.find(fresh.team_id, external_id=grant.external_id)
+ if row is None:
+ try:
+ row = oauth.create(
+ fresh.team_id,
+ external_id=grant.external_id,
+ config=grant.config,
+ sensitive_config=grant.sensitive_config,
+ created_by_id=fresh.created_by_id,
+ )
+ except IntegrationConflict:
+ row = oauth.find(fresh.team_id, external_id=grant.external_id)
+ if row is None:
+ raise
+
+ new_inputs = {key: value for key, value in fresh_inputs.items() if key not in grant.legacy_keys}
+ new_inputs[grant.pointer_key] = row.id
+ SourceInputsStore.adopt_oauth_pointer(fresh, new_inputs, IntegrationReference.from_legacy_id(row.id))
+ return HUBSPOT_LEGACY_ADOPTED
+
+
def _sync_source(source: ExternalDataSource) -> str:
"""Write the reference (and for typed-in credentials the row) of one source from its stored `job_inputs`,
read again under the source lock.
diff --git a/products/warehouse_sources/backend/logic/source_inputs.py b/products/warehouse_sources/backend/logic/source_inputs.py
index eaf5a067990b..f8553b7f7f9b 100644
--- a/products/warehouse_sources/backend/logic/source_inputs.py
+++ b/products/warehouse_sources/backend/logic/source_inputs.py
@@ -90,6 +90,18 @@ class SourceInputsStore:
source.credentials_integration_id = None if reference is None else str(reference)
source.save(update_fields=["credentials_integration_id"])
+ @staticmethod
+ def adopt_oauth_pointer(
+ source: ExternalDataSource, inputs: Mapping[str, Any], reference: IntegrationReference
+ ) -> None:
+ """Save adopted OAuth inputs and their reference together, without the typed-in credentials mirror.
+
+ The caller must hold the source lock and create the integration in the same transaction.
+ """
+ _stage(source, inputs)
+ source.credentials_integration_id = str(reference)
+ source.save(update_fields=[*INPUTS_UPDATE_FIELDS])
+
@staticmethod
def load_settings(source: ExternalDataSource) -> dict[str, Any]:
"""Only the sync settings and runtime state of the source, never a connection field.
diff --git a/products/warehouse_sources/backend/management/commands/backfill_warehouse_source_credentials.py b/products/warehouse_sources/backend/management/commands/backfill_warehouse_source_credentials.py
index c12c5ac9ebad..9b6dbd27111e 100644
--- a/products/warehouse_sources/backend/management/commands/backfill_warehouse_source_credentials.py
+++ b/products/warehouse_sources/backend/management/commands/backfill_warehouse_source_credentials.py
@@ -10,10 +10,11 @@ from products.warehouse_sources.backend.management.commands._credentials_report
class Command(BaseCommand):
help = (
- "Create or update the credentials row of each non-deleted warehouse source with typed-in credentials from "
- "its stored job_inputs, and store the reference to a new row in job_inputs. A source with an OAuth "
- "connection gets no row. Previews by default; pass --execute to write. Safe to repeat. Never prints "
- "field values."
+ "Create or update credentials rows from stored job_inputs for non-deleted warehouse sources with typed-in credentials. "
+ "Link OAuth pointers to the credentials_integration_id column. "
+ "Move legacy HubSpot tokens into a hubspot integration row. "
+ "Preview by default; pass --execute to write. Network calls to HubSpot happen only with --execute. "
+ "Safe to repeat. Never prints field values."
)
def add_arguments(self, parser: CommandParser) -> None:
diff --git a/products/warehouse_sources/backend/management/commands/reconcile_warehouse_source_credentials.py b/products/warehouse_sources/backend/management/commands/reconcile_warehouse_source_credentials.py
index f3d2ceaaaba4..296f5f3af73e 100644
--- a/products/warehouse_sources/backend/management/commands/reconcile_warehouse_source_credentials.py
+++ b/products/warehouse_sources/backend/management/commands/reconcile_warehouse_source_credentials.py
@@ -7,6 +7,7 @@ from django.core.management.base import BaseCommand, CommandError, CommandParser
from products.warehouse_sources.backend.logic.source_credentials_sync import (
CREATED,
+ HUBSPOT_LEGACY_ADOPTED,
NOT_BACKFILLED,
OAUTH_LINKED,
RECREATED,
@@ -21,6 +22,7 @@ VERIFY_LABELS = {
RECREATED: "missing_row",
UPDATED: "differs_or_unreadable_row",
OAUTH_LINKED: "oauth_reference_not_in_column",
+ HUBSPOT_LEGACY_ADOPTED: "legacy_oauth_tokens_in_job_inputs",
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
index 6e69d05d8c2a..5353c6718948 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
@@ -37,6 +37,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.con
from products.warehouse_sources.backend.temporal.data_imports.sources.common.credential_kind import (
default_credential_kind,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.legacy_oauth import LegacyOAuthGrant
from products.warehouse_sources.backend.temporal.data_imports.sources.common.oauth_pointers import (
OAuthPointer,
PointerPath,
@@ -614,6 +615,17 @@ class _BaseSource(ABC, Generic[ConfigType]):
return derive_credential_auth_type(self.get_source_config)
+ def has_legacy_oauth_tokens(self, job_inputs: Mapping[str, Any]) -> bool:
+ """Check for legacy OAuth tokens without network calls."""
+ return False
+
+ def adopt_legacy_oauth(self, job_inputs: Mapping[str, Any]) -> LegacyOAuthGrant | None:
+ """Prepare a grant for storage. This method can make network calls and raise LegacyOAuthGrantUnusable.
+
+ None means the inputs hold no legacy OAuth tokens to move into a row.
+ """
+ return None
+
def in_use_oauth_slot(self, job_inputs: Mapping[str, Any]) -> PointerPath | None:
"""Where ``job_inputs`` keep the OAuth pointer (`*_integration_id`) that the sync uses, or None.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/legacy_oauth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/legacy_oauth.py
new file mode 100644
index 000000000000..b6ab63180411
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/legacy_oauth.py
@@ -0,0 +1,20 @@
+from collections.abc import Mapping
+from dataclasses import field
+from typing import Any
+
+from posthog.dataclasses import frozen
+
+
+@frozen
+class LegacyOAuthGrant:
+ kind: str
+ external_id: str
+ config: Mapping[str, Any]
+ sensitive_config: Mapping[str, Any] = field(repr=False)
+ pointer_key: str
+ legacy_keys: tuple[str, ...]
+ refresh_token: str = field(repr=False)
+
+
+class LegacyOAuthGrantUnusable(Exception):
+ """The legacy tokens cannot be used. Messages must not contain tokens."""
diff --git a/products/warehouse_sources/backend/tests/management/test_hubspot_legacy_credentials.py b/products/warehouse_sources/backend/tests/management/test_hubspot_legacy_credentials.py
new file mode 100644
index 000000000000..8830791d9eff
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/management/test_hubspot_legacy_credentials.py
@@ -0,0 +1,223 @@
+import time
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from django.core.management.base import CommandError
+from django.test import override_settings
+
+from parameterized import parameterized
+
+from posthog.integrations import IntegrationManager, IntegrationReference
+
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.tests.management.test_source_credentials_commands import (
+ _CredentialsCommandTestCase,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+from products.warehouse_sources.sources.hubspot.auth import HubspotLegacyGrant, hubspot_refresh_access_token
+from products.warehouse_sources.sources.sdk import LegacyOAuthGrantUnusable
+
+EXCHANGE = "products.warehouse_sources.sources.hubspot.source.hubspot_exchange_legacy_grant"
+LEGACY_INPUTS: dict[str, Any] = {"hubspot_secret_key": "fake-access", "hubspot_refresh_token": "fake-refresh"}
+HUB_ID = "424242"
+
+
+def _grant(**overrides: Any) -> HubspotLegacyGrant:
+ values: dict[str, Any] = {
+ "external_id": HUB_ID,
+ "config": {
+ "hub_id": int(HUB_ID),
+ "hub_domain": "example.com",
+ "user": "[email protected]",
+ "user_id": 1,
+ "scopes": ["oauth"],
+ "expires_in": 1800,
+ },
+ "access_token": "fake-new-access",
+ "refresh_token": "fake-refresh",
+ }
+ return HubspotLegacyGrant(**{**values, **overrides})
+
+
+class TestHubspotLegacyAdoption(_CredentialsCommandTestCase):
+ def _legacy_source(self, **kwargs: Any) -> ExternalDataSource:
+ return self._source(dict(LEGACY_INPUTS), source_type=ExternalDataSourceType.HUBSPOT, **kwargs)
+
+ def _stored(self, source: ExternalDataSource) -> dict[str, Any]:
+ return SourceInputsStore.load_stored(ExternalDataSource.objects.get(pk=source.pk))
+
+ def _hubspot_rows(self) -> list[Any]:
+ return IntegrationManager.hubspot.oauth.list(self.team.pk)
+
+ def _adopt(self, *args: str) -> str:
+ return self._run("backfill_warehouse_source_credentials", "--source-type", "Hubspot", "--execute", *args)
+
+ @parameterized.expand([("new_row", False), ("existing_row_for_the_same_hub", True)])
+ def test_legacy_source_moves_into_a_hubspot_row(self, _name: str, row_exists: bool) -> None:
+ existing = None
+ if row_exists:
+ existing = IntegrationManager.hubspot.oauth.create(
+ self.team.pk,
+ external_id=HUB_ID,
+ config={"hub_id": int(HUB_ID)},
+ sensitive_config={"access_token": "fake-other", "refresh_token": "fake-other-refresh"},
+ )
+ source = self._legacy_source()
+
+ with patch(EXCHANGE, return_value=_grant()):
+ output = self._adopt()
+
+ assert "hubspot_legacy_adopted=1" in output
+ rows = self._hubspot_rows()
+ assert len(rows) == 1
+ row = rows[0]
+ if existing is not None:
+ assert row.id == existing.id
+ assert row.refresh_token == "fake-other-refresh"
+ else:
+ assert row.integration_id == HUB_ID
+ assert row.access_token == "fake-new-access"
+ assert row.refresh_token == "fake-refresh"
+ assert row.config["hub_domain"] == "example.com"
+ assert row.config["expires_in"] == 1800
+ assert abs(row.config["refreshed_at"] - time.time()) < 60
+ assert self._stored(source) == {"hubspot_integration_id": str(row.id)}
+ assert self._reference(source) == str(IntegrationReference.from_legacy_id(row.id))
+ assert "fake-" not in output
+
+ def test_preview_writes_nothing_and_calls_no_network(self) -> None:
+ source = self._legacy_source()
+
+ with patch(EXCHANGE) as exchange:
+ output = self._run("backfill_warehouse_source_credentials", "--source-type", "Hubspot")
+
+ assert "hubspot_legacy_adopted=1" in output
+ exchange.assert_not_called()
+ assert self._hubspot_rows() == []
+ assert self._stored(source) == LEGACY_INPUTS
+ assert self._reference(source) is None
+
+ def test_second_run_changes_nothing(self) -> None:
+ source = self._legacy_source()
+ with patch(EXCHANGE, return_value=_grant()) as exchange:
+ self._adopt()
+ stored = self._stored(source)
+ output = self._adopt()
+
+ assert exchange.call_count == 1
+ assert "hubspot_legacy_adopted" not in output
+ assert "unchanged=1" in output
+ assert self._stored(source) == stored
+ assert len(self._hubspot_rows()) == 1
+
+ @parameterized.expand(
+ [
+ ("token_rejected", LegacyOAuthGrantUnusable("rejected")),
+ ("hubspot_unreachable", LegacyOAuthGrantUnusable("unreachable")),
+ ]
+ )
+ def test_unusable_token_is_skipped_and_counted(self, _name: str, error: Exception) -> None:
+ source = self._legacy_source()
+
+ with patch(EXCHANGE, side_effect=error):
+ output = self._adopt()
+
+ assert "skipped_legacy_token_unusable=1" in output
+ assert self._hubspot_rows() == []
+ assert self._stored(source) == LEGACY_INPUTS
+ assert self._reference(source) is None
+
+ def test_refresh_token_changed_during_the_exchange_is_skipped(self) -> None:
+ source = self._legacy_source()
+
+ with patch(EXCHANGE, return_value=_grant(refresh_token="fake-rotated")):
+ # The grant holds the token that the inputs had when the exchange ran.
+ with patch.object(
+ SourceInputsStore,
+ "load_stored",
+ side_effect=[
+ dict(LEGACY_INPUTS),
+ dict(LEGACY_INPUTS),
+ {**LEGACY_INPUTS, "hubspot_refresh_token": "fake-changed"},
+ ],
+ ):
+ output = self._adopt()
+
+ assert "skipped_legacy_token_unusable=1" in output
+ assert self._hubspot_rows() == []
+ assert self._stored(source) == LEGACY_INPUTS
+
+ @parameterized.expand(
+ [
+ ("pointer_only", {"hubspot_integration_id": "7"}),
+ ("pointer_and_leftover_token", {"hubspot_integration_id": "7", "hubspot_refresh_token": "fake-refresh"}),
+ ]
+ )
+ def test_modern_source_is_not_exchanged(self, _name: str, inputs: dict[str, Any]) -> None:
+ source = self._source(inputs, source_type=ExternalDataSourceType.HUBSPOT)
+
+ with patch(EXCHANGE) as exchange:
+ self._adopt()
+
+ exchange.assert_not_called()
+ assert self._hubspot_rows() == []
+ assert self._stored(source) == inputs
+
+ def test_verify_reports_a_legacy_source_until_it_moves(self) -> None:
+ self._legacy_source()
+
+ with self.assertRaises(CommandError):
+ self._run("reconcile_warehouse_source_credentials", "--verify", "--source-type", "Hubspot")
+
+ with patch(EXCHANGE, return_value=_grant()):
+ self._adopt()
+
+ output = self._run("reconcile_warehouse_source_credentials", "--verify", "--source-type", "Hubspot")
+ assert "Verified" in output
+
+ def test_converted_source_refreshes_through_its_integration(self) -> None:
+ source = self._legacy_source()
+ with patch(EXCHANGE, return_value=_grant()):
+ self._adopt()
+ row = self._hubspot_rows()[0]
+ IntegrationManager.hubspot.oauth.update(
+ self.team.pk, row.id, config_patch={"refreshed_at": int(time.time()) - 100000}
+ )
+ response = MagicMock(status_code=200)
+ response.json.return_value = {"access_token": "fake-refreshed", "expires_in": 1800}
+
+ with (
+ override_settings(HUBSPOT_APP_CLIENT_ID="fake-id", HUBSPOT_APP_CLIENT_SECRET="fake-secret"),
+ patch("posthog.models.integration.oauth.requests.post", return_value=response) as post,
+ ):
+ refreshed = IntegrationManager.hubspot.oauth.refresh_access_token(self.team.pk, row.id)
+
+ assert post.call_args.kwargs["data"]["refresh_token"] == "fake-refresh"
+ assert refreshed.access_token == "fake-refreshed"
+ assert self._stored(source) == {"hubspot_integration_id": str(row.id)}
+
+ def test_stale_legacy_write_after_conversion_does_not_restore_the_keys(self) -> None:
+ source = self._legacy_source()
+ with patch(EXCHANGE, return_value=_grant()):
+ self._adopt()
+ converted = self._stored(source)
+ response = MagicMock(status_code=200)
+ response.json.return_value = {"access_token": "fake-late"}
+ session = MagicMock()
+ session.post.return_value = response
+
+ with (
+ patch("products.warehouse_sources.sources.hubspot.auth.make_tracked_session", return_value=session),
+ patch(
+ "products.warehouse_sources.sources.hubspot.auth._hubspot_app_credentials",
+ return_value={"client_id": "fake-id", "client_secret": "fake-secret"},
+ ),
+ ):
+ hubspot_refresh_access_token("fake-refresh", source_id=str(source.id))
+
+ assert self._stored(source) == converted
+ assert self._reference(source) == str(
+ IntegrationReference.from_legacy_id(int(converted["hubspot_integration_id"]))
+ )
diff --git a/products/warehouse_sources/sources/hubspot/auth.py b/products/warehouse_sources/sources/hubspot/auth.py
index f8187d786298..c3481cbdef69 100644
--- a/products/warehouse_sources/sources/hubspot/auth.py
+++ b/products/warehouse_sources/sources/hubspot/auth.py
@@ -1,8 +1,21 @@
+from collections.abc import Mapping
+from dataclasses import field
+from typing import cast
+
+from django.db import transaction
+
import requests
import structlog
from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
-from products.warehouse_sources.sources.sdk import credentials_service, make_tracked_session
+from products.warehouse_sources.sources.sdk import (
+ ExternalDataSource,
+ LegacyOAuthGrantUnusable,
+ credentials_service,
+ frozen,
+ make_tracked_session,
+ redact_request_urls,
+)
from products.warehouse_sources.sources.sdk.internals import SourceInputsStore
logger = structlog.get_logger(__name__)
@@ -23,6 +36,18 @@ class HubspotRetryableError(Exception):
self.retry_after = retry_after
+class HubspotTokenRefreshError(Exception):
+ """HubSpot rejected the token refresh."""
+
+
+@frozen
+class HubspotLegacyGrant:
+ external_id: str
+ config: Mapping[str, object]
+ access_token: str = field(repr=False)
+ refresh_token: str = field(repr=False)
+
+
def _parse_retry_after(res: requests.Response) -> float | None:
"""HubSpot sends Retry-After as delta-seconds on 429s; ignore other (non-numeric) forms."""
raw = res.headers.get("Retry-After")
@@ -70,7 +95,7 @@ def _hubspot_app_credentials() -> dict[str, str]:
wait=_wait_strategy,
reraise=True,
)
-def hubspot_refresh_access_token(refresh_token: str, source_id: str | None = None) -> str:
+def _hubspot_refresh_token_payload(refresh_token: str) -> Mapping[str, object]:
res = make_tracked_session().post(
"https://api.hubapi.com/oauth/v1/token",
data={
@@ -93,9 +118,16 @@ def hubspot_refresh_access_token(refresh_token: str, source_id: str | None = Non
# and retry rather than failing the sync (and disabling the schema) on a transient state.
if "migration in progress" in err_message.lower():
raise HubspotRetryableError(err_message)
- raise Exception(err_message)
+ raise HubspotTokenRefreshError(err_message)
- access_token = res.json()["access_token"]
+ payload = res.json()
+ if not isinstance(payload, Mapping):
+ raise HubspotTokenRefreshError("HubSpot returned an invalid token response")
+ return payload
+
+
+def hubspot_refresh_access_token(refresh_token: str, source_id: str | None = None) -> str:
+ access_token = cast(str, _hubspot_refresh_token_payload(refresh_token)["access_token"])
if source_id:
_update_source_job_inputs(source_id, access_token)
@@ -103,6 +135,44 @@ def hubspot_refresh_access_token(refresh_token: str, source_id: str | None = Non
return access_token
+def hubspot_exchange_legacy_grant(refresh_token: str) -> HubspotLegacyGrant:
+ if not refresh_token:
+ raise LegacyOAuthGrantUnusable("The legacy refresh token is missing")
+ try:
+ payload = _hubspot_refresh_token_payload(refresh_token)
+ access_token = payload.get("access_token")
+ if not isinstance(access_token, str) or not access_token:
+ raise LegacyOAuthGrantUnusable("HubSpot returned no access token")
+ rotated_refresh_token = payload.get("refresh_token") or refresh_token
+ if not isinstance(rotated_refresh_token, str):
+ raise LegacyOAuthGrantUnusable("HubSpot returned an invalid refresh token")
+ # The token is part of the URL, so transport logs must hide it.
+ with redact_request_urls():
+ res = make_tracked_session().get(
+ "https://api.hubapi.com/oauth/v1/access-tokens/" + access_token,
+ )
+ if res.status_code != 200:
+ raise LegacyOAuthGrantUnusable("HubSpot rejected the token information request")
+ token_info = res.json()
+ if not isinstance(token_info, Mapping):
+ raise LegacyOAuthGrantUnusable("HubSpot returned invalid token information")
+ hub_id = token_info.get("hub_id")
+ if isinstance(hub_id, bool) or not isinstance(hub_id, (int, str)) or not hub_id:
+ raise LegacyOAuthGrantUnusable("HubSpot returned no hub id")
+ config = {
+ key: value for key, value in payload.items() if key not in {"access_token", "refresh_token", "id_token"}
+ }
+ config.update({key: token_info.get(key) for key in ("hub_id", "hub_domain", "user", "user_id", "scopes")})
+ return HubspotLegacyGrant(
+ external_id=str(hub_id),
+ config=config,
+ access_token=access_token,
+ refresh_token=rotated_refresh_token,
+ )
+ except (HubspotTokenRefreshError, HubspotRetryableError, requests.RequestException, ValueError):
+ raise LegacyOAuthGrantUnusable("The legacy HubSpot grant could not be exchanged") from None
+
+
def hubspot_access_token_is_valid(access_token: str) -> bool:
res = make_tracked_session().get(
"https://api.hubapi.com/oauth/v1/access-tokens/" + access_token,
@@ -111,19 +181,18 @@ def hubspot_access_token_is_valid(access_token: str) -> bool:
def _update_source_job_inputs(source_id: str, access_token: str) -> None:
- from products.warehouse_sources.sources.sdk import ExternalDataSource
-
try:
- # nosemgrep: idor-lookup-without-team -- pre-existing, file moved out of temporal/; source_id comes from the sync job, not a request
- source = ExternalDataSource.objects.get(id=source_id)
- job_inputs = SourceInputsStore.load(source)
+ with transaction.atomic():
+ # nosemgrep: idor-lookup-without-team -- pre-existing, file moved out of temporal/; source_id comes from the sync job, not a request
+ source = ExternalDataSource.objects.select_related(None).select_for_update(of=("self",)).get(id=source_id)
+ job_inputs = SourceInputsStore.load_stored(source)
- # Only persist for legacy sources that store credentials directly in job_inputs
- if "hubspot_integration_id" in job_inputs:
- return
+ # Only persist for legacy sources that store credentials directly in job_inputs
+ if "hubspot_integration_id" in job_inputs:
+ return
- # Not `save`: a token refresh never changes the row that the source uses, so it leaves the reference column alone.
- SourceInputsStore.update_oauth_inputs(source, {"hubspot_secret_key": access_token}, extra_update_fields=())
+ # Not `save`: a token refresh never changes the row that the source uses, so it leaves the reference column alone.
+ SourceInputsStore.update_oauth_inputs(source, {"hubspot_secret_key": access_token}, extra_update_fields=())
except Exception:
logger.exception("Failed to update job_inputs after HubSpot token refresh", source_id=source_id)
diff --git a/products/warehouse_sources/sources/hubspot/source.py b/products/warehouse_sources/sources/hubspot/source.py
index 1a96ddb2e954..7151d5ab68e6 100644
--- a/products/warehouse_sources/sources/hubspot/source.py
+++ b/products/warehouse_sources/sources/hubspot/source.py
@@ -1,9 +1,15 @@
-from typing import cast
+import time
+from collections.abc import Mapping
+from typing import Any, cast
import structlog
from products.warehouse_sources.sources.hubspot._config import HubspotSourceConfig
-from products.warehouse_sources.sources.hubspot.auth import hubspot_access_token_is_valid, hubspot_refresh_access_token
+from products.warehouse_sources.sources.hubspot.auth import (
+ hubspot_access_token_is_valid,
+ hubspot_exchange_legacy_grant,
+ hubspot_refresh_access_token,
+)
from products.warehouse_sources.sources.hubspot.hubspot import HubspotResumeConfig, hubspot_source
from products.warehouse_sources.sources.hubspot.scopes import (
SCOPE_GATED_OBJECTS,
@@ -25,6 +31,7 @@ from products.warehouse_sources.sources.sdk import (
DataWarehouseSourceCategory,
ExternalDataSourceType,
FieldType,
+ LegacyOAuthGrant,
OAuthMixin,
ResumableSource,
ResumableSourceManager,
@@ -142,6 +149,29 @@ class HubspotSource(ResumableSource[HubspotSourceConfig | HubspotSourceOldConfig
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.HUBSPOT
+ def has_legacy_oauth_tokens(self, job_inputs: Mapping[str, Any]) -> bool:
+ refresh_token = job_inputs.get("hubspot_refresh_token")
+ return "hubspot_integration_id" not in job_inputs and isinstance(refresh_token, str) and bool(refresh_token)
+
+ def adopt_legacy_oauth(self, job_inputs: Mapping[str, Any]) -> LegacyOAuthGrant | None:
+ if not self.has_legacy_oauth_tokens(job_inputs):
+ return None
+ refresh_token = cast(str, job_inputs["hubspot_refresh_token"])
+ exchanged = hubspot_exchange_legacy_grant(refresh_token)
+ return LegacyOAuthGrant(
+ kind="hubspot",
+ external_id=exchanged.external_id,
+ config={**exchanged.config, "refreshed_at": int(time.time())},
+ sensitive_config={
+ "access_token": exchanged.access_token,
+ "refresh_token": exchanged.refresh_token,
+ "id_token": None,
+ },
+ pointer_key="hubspot_integration_id",
+ legacy_keys=("hubspot_secret_key", "hubspot_refresh_token"),
+ refresh_token=refresh_token,
+ )
+
def get_canonical_descriptions(self) -> CanonicalDescriptions:
from products.warehouse_sources.sources.hubspot.canonical_descriptions import CANONICAL_DESCRIPTIONS
diff --git a/products/warehouse_sources/sources/hubspot/test/test_hubspot_auth.py b/products/warehouse_sources/sources/hubspot/test/test_hubspot_auth.py
index 5e5efac9b30c..7ed880812e23 100644
--- a/products/warehouse_sources/sources/hubspot/test/test_hubspot_auth.py
+++ b/products/warehouse_sources/sources/hubspot/test/test_hubspot_auth.py
@@ -205,14 +205,16 @@ def test_token_refresh_saves_the_token_only_for_a_source_with_its_own_token(
with (
_patch_post(response),
+ patch("products.warehouse_sources.sources.hubspot.auth.transaction.atomic"),
patch.object(ExternalDataSource, "objects") as objects,
- patch.object(SourceInputsStore, "load", return_value=stored_inputs),
+ patch.object(SourceInputsStore, "load_stored", return_value=stored_inputs),
patch.object(SourceInputsStore, "update_oauth_inputs") as update_oauth_inputs,
):
- objects.get.return_value = source
+ locked_sources = objects.select_related.return_value.select_for_update.return_value
+ locked_sources.get.return_value = source
assert hubspot_refresh_access_token("fake-refresh", source_id="source-id") == "fake-new"
- objects.get.assert_called_once_with(id="source-id")
+ locked_sources.get.assert_called_once_with(id="source-id")
if expected_write:
# Not a full save, so the reference column keeps its value.
update_oauth_inputs.assert_called_once_with(source, {"hubspot_secret_key": "fake-new"}, extra_update_fields=())
diff --git a/products/warehouse_sources/sources/sdk/__init__.py b/products/warehouse_sources/sources/sdk/__init__.py
index 55ddb4a74509..7de3d64a2fd1 100644
--- a/products/warehouse_sources/sources/sdk/__init__.py
+++ b/products/warehouse_sources/sources/sdk/__init__.py
@@ -167,6 +167,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.int
from products.warehouse_sources.backend.temporal.data_imports.sources.common.interruptible_wait import (
interruptible_wait,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.legacy_oauth import (
+ LegacyOAuthGrant,
+ LegacyOAuthGrantUnusable,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (
DATABASE_HOST_NOT_ALLOWED_ERROR,
CredentialAccountsMixin,
@@ -453,6 +457,8 @@ __all__ = [
"JSONResponseCursorPaginatorConfig",
"JSONResponsePaginator",
"KEYWORDS",
+ "LegacyOAuthGrant",
+ "LegacyOAuthGrantUnusable",
"MARKETING_ANALYTICS_SUGGESTED_TABLE_TOOLTIP",
"MAX_EXCEL_FILE_BYTES",
"MetaAdsIntegration",