: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(warehouse-sources): server-manage custom oauth2 credential rows (#66792)
Marcus Hofdf69f9068976
diff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.pyindex 0cf28ec6976f..086fe047f0a7 100644--- a/products/data_warehouse/backend/presentation/views/external_data_source.py+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py@@ -914,6 +914,16 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializerelse:new_job_inputs.pop(key, None)+ # The OAuth2 integration row pointer is server-managed: pin it to the stored value so an+ # editor can't repoint the source at a different row (and through it, different credentials).+ # Re-entered auth_oauth2_* secrets flow into the pinned row during credential validation.+ if source_type_model == ExternalDataSourceType.CUSTOM:+ existing_oauth2_pointer = existing_job_inputs.get("auth_oauth2_integration_id")+ if existing_oauth2_pointer:+ new_job_inputs["auth_oauth2_integration_id"] = existing_oauth2_pointer+ else:+ new_job_inputs.pop("auth_oauth2_integration_id", None)+# If the connection target changed, require credentials to be re-entered. Covers# both the generic `host` field and source-specific URL fields like ServiceNow's# `instance_url`, so a stored credential can't be redirected to a new host.@@ -947,22 +957,33 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializerexisting_hosts = manifest_request_hosts(existing_job_inputs.get("manifest_json"))manifest_host_added = bool(new_hosts - existing_hosts)- # An integration-backed OAuth2 custom source carries no secret in job_inputs — the client secret +- # tokens live in the CustomOAuth2Integration row and are injected at sync time, keyed by the- # non-secret `auth_oauth2_integration_id`. So `has_preserved_credentials` never sees a preserved- # secret for it, yet a host change would still redirect that injected token to the new host. A source- # that still has a bound integration row is preserving that credential — and clearing the job_inputs- # pointer does NOT unbind the row, so keying off the pointer alone let an editor clear it, move the- # host, then re-add the pointer to redirect the still-bound token. Gate on the actual row binding too.- source_has_bound_integration = source_type_model == ExternalDataSourceType.CUSTOM and (- CustomOAuth2Integration.objects.for_team(instance.team_id).filter(external_data_source=instance).exists()- )- existing_integration_id = existing_job_inputs.get("auth_oauth2_integration_id")- preserved_oauth2_integration = source_has_bound_integration or (- bool(existing_integration_id)- and incoming_job_inputs.get("auth_oauth2_integration_id", existing_integration_id)- == existing_integration_id- )+ # A row-backed OAuth2 custom source carries no secret in job_inputs — the client secret ++ # tokens live in the bound CustomOAuth2Integration row and are injected at sync time. So+ # `has_preserved_credentials` never sees a preserved secret for it, yet a host change would+ # still redirect the row's injected token to the new host. Re-entering every secret the row+ # holds satisfies the gate the same way typing a password does for other sources: because a+ # config change makes adoption replace the row's secrets with the typed ones outright (see+ # _apply_oauth2_material — the rotated-token keep-rule is suspended on config change), only+ # material the editor provably possesses is ever sent to the new host.+ bound_integration = None+ if source_type_model == ExternalDataSourceType.CUSTOM:+ bound_integration = (+ CustomOAuth2Integration.objects.for_team(instance.team_id).filter(external_data_source=instance).first()+ )+ reentered_oauth2_secrets = False+ if bound_integration is not None:+ held_secret_fields = [+ incoming_field+ for row_key, incoming_field in (+ ("client_secret", "auth_oauth2_client_secret"),+ ("refresh_token", "auth_oauth2_refresh_token"),+ )+ if bound_integration.sensitive_config.get(row_key)+ ]+ reentered_oauth2_secrets = bool(held_secret_fields) and all(+ bool(incoming_job_inputs.get(field)) for field in held_secret_fields+ )+ preserved_oauth2_integration = bound_integration is not None and not reentered_oauth2_secretsif connection_host_changed or ssh_tunnel_changed or manifest_host_added:gate_sensitive_fields = sensitive_fields - _CREATION_ONLY_SECRET_FIELDS@@ -1089,6 +1110,16 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializerfallback=instance.connection_metadata,)+ if job_inputs_were_submitted and isinstance(source, CustomSource):+ # Credential validation adopts re-entered OAuth2 secrets into the integration row and+ # rewrites the config (pointer set, static secrets cleared) — re-serialize so job_inputs+ # stores the pointer and never the raw secrets.+ validated_job_inputs = source_config.to_dict()+ for key in _CDC_EXPOSED_JOB_INPUT_KEYS:+ if key in existing_job_inputs:+ validated_job_inputs[key] = existing_job_inputs[key]+ validated_data["job_inputs"] = validated_job_inputs+updated_source: ExternalDataSource = super().update(instance, validated_data)if updated_source.is_direct_query and discovered_schemas is not None:@@ -1750,6 +1781,17 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixidirect_query_enabled=direct_query_enabled,)+ if source_type_model == ExternalDataSourceType.CUSTOM:+ # Claim the OAuth2 integration row for the new source right away instead of waiting for the+ # first sync's trust-on-first-use claim, closing the window where another create by the same+ # user (matching the same unbound row) could adopt it. The guarded filter makes a lost race+ # a no-op; sync-time authorization remains the backstop.+ oauth2_integration_id = (new_source_model.job_inputs or {}).get("auth_oauth2_integration_id")+ if oauth2_integration_id:+ CustomOAuth2Integration.objects.for_team(self.team_id).filter(+ id=oauth2_integration_id, external_data_source__isnull=True+ ).update(external_data_source=new_source_model)+# CDC: gate per-source-type adapter availability up front so downstream blocks# can `if cdc_enabled` without repeating the source-type check.try:@@ -2729,6 +2771,18 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiif error_response is not None or source_config is None:return error_response or Response(status=status.HTTP_400_BAD_REQUEST)+ if isinstance(source, CustomSource):+ # Validation may have adopted static OAuth2 secrets into an integration row and rewritten+ # the config to point at it. `_create_external_data_source` below re-parses the raw payload+ # (it skips the credential gate), so propagate the rewrite onto the payload — the created+ # source must store the row pointer, never the raw secrets.+ validated_payload = source_config.to_dict()+ for key in ("auth_oauth2_integration_id", "auth_oauth2_client_secret", "auth_oauth2_refresh_token"):+ if validated_payload.get(key):+ payload[key] = validated_payload[key]+ else:+ payload.pop(key, None)+try:source_schemas = source.get_schemas(source_config, self.team_id)except NotImplementedError:@@ -3006,6 +3060,11 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiaccess_method: str = ExternalDataSource.AccessMethod.WAREHOUSE,) -> tuple[Response | None, Config | None]:"""Run the config + live credential gate (including the SSRF host check) for a source payload."""+ if isinstance(source, CustomSource):+ # The OAuth2 integration row pointer is server-managed: validation derives it by adopting+ # the submitted auth_oauth2_* secrets into a row. Never trust a client-supplied pointer on+ # a pre-create seam — it could reference a row the caller shouldn't consume.+ payload.pop("auth_oauth2_integration_id", None)is_valid, errors = source.validate_config(payload)if not is_valid:return (diff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.pyindex b15ac9eb81c1..69cb05b68603 100644--- a/products/data_warehouse/backend/tests/api/test_external_data_source.py+++ b/products/data_warehouse/backend/tests/api/test_external_data_source.py@@ -5248,21 +5248,35 @@ class TestExternalDataSource(APIBaseTest):)@parameterized.expand(- [("preserved_integration", {}, 400), ("cleared_integration", {"auth_oauth2_integration_id": ""}, 200)]+ [+ ("no_reentry", {}, 400),+ ("partial_reentry", {"auth_oauth2_client_secret": "cs_new"}, 400),+ (+ "full_reentry",+ {"auth_oauth2_client_secret": "cs_new", "auth_oauth2_refresh_token": "rt_new"},+ 200,+ ),+ ])@patch("products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.CustomSource.validate_credentials",return_value=(True, None),)- def test_update_custom_oauth2_integration_source_host_change_requires_reentry(+ def test_update_custom_oauth2_row_backed_source_host_change_requires_full_reentry(self, _name, extra_inputs, expected_status, mock_validate_credentials):- # An integration-backed OAuth2 source keeps no secret in job_inputs — the token lives in the- # CustomOAuth2Integration row and is injected at sync time keyed by the non-secret- # auth_oauth2_integration_id. So a manifest host change that preserves that pointer would still- # redirect the injected token to the new host; the gate must treat the preserved pointer like a- # preserved secret. Clearing the pointer is an explicit re-config and is allowed.+ # A row-backed OAuth2 source keeps no secret in job_inputs — the token lives in the bound+ # CustomOAuth2Integration row and is injected at sync time. A manifest host change would still+ # redirect the row's injected token, so the gate fires unless the editor re-enters every secret+ # the row holds (which validation then rotates into the row) — a partial re-entry still+ # preserves a secret the editor may not know.source = self._custom_oauth2_integration_source()+ CustomOAuth2Integration.objects.for_team(self.team.pk).create(+ team=self.team,+ external_data_source=source,+ config={"client_id": "cid", "token_url": "https://auth.example.com/token"},+ sensitive_config={"client_secret": "cs", "refresh_token": "rt"},+ )new_manifest = {"client": {"base_url": "https://attacker.example.net",@@ -5313,6 +5327,180 @@ class TestExternalDataSource(APIBaseTest):assert "re-entering your credentials" in str(response.json())mock_validate_credentials.assert_not_called()+ def _valid_oauth2_manifest(self) -> dict:+ return {+ "client": {+ "base_url": "https://api.example.com",+ "auth": {+ "type": "oauth2",+ "client_id": "cid",+ "token_url": "https://auth.example.com/token",+ "grant_type": "refresh_token",+ },+ },+ "resources": [+ {"name": "users", "primary_key": "id", "endpoint": {"path": "/users", "data_selector": "data"}}+ ],+ }++ def _mock_oauth2_network(self, mock_token_session, mock_probe_session) -> None:+ token_response = MagicMock()+ token_response.status_code = 200+ token_response.raw.read.return_value = json.dumps(+ {"access_token": "minted-AT", "expires_in": 3600, "refresh_token": "rotated-RT"}+ ).encode()+ mock_token_session.return_value.post.return_value = token_response+ mock_probe_session.return_value.request.return_value = MagicMock(status_code=200, text="{}")++ @patch(+ "products.data_warehouse.backend.presentation.views.external_data_source.trigger_external_data_source_workflow"+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.make_tracked_session")+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth.make_tracked_session"+ )+ def test_create_custom_oauth2_source_adopts_secrets_into_bound_row(+ self, mock_token_session, mock_probe_session, _mock_trigger+ ):+ # The whole flow through the real create endpoint: secrets typed on the source config screen+ # end up in a CustomOAuth2Integration row bound to the new source, and the persisted+ # job_inputs carry only the server-written pointer — never the raw secrets. A client-supplied+ # pointer is dropped, so it cannot pre-seed the adoption.+ self._mock_oauth2_network(mock_token_session, mock_probe_session)++ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/",+ data={+ "source_type": "Custom",+ "prefix": "customoauth_",+ "payload": {+ "manifest_json": json.dumps(self._valid_oauth2_manifest()),+ "auth_oauth2_client_secret": "cs",+ "auth_oauth2_refresh_token": "orig-RT",+ "auth_oauth2_integration_id": "22222222-2222-2222-2222-222222222222",+ "schemas": [{"name": "users", "should_sync": True, "sync_type": "full_refresh"}],+ },+ },+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ source = ExternalDataSource.objects.get(id=response.json()["id"])+ row = CustomOAuth2Integration.objects.for_team(self.team.pk).get()+ assert source.job_inputs["auth_oauth2_integration_id"] == str(row.pk)+ assert not source.job_inputs.get("auth_oauth2_client_secret")+ assert not source.job_inputs.get("auth_oauth2_refresh_token")+ assert row.external_data_source_id == source.pk+ assert row.created_by_id == self.user.pk+ assert row.sensitive_config["client_secret"] == "cs"+ assert row.sensitive_config["refresh_token"] == "rotated-RT"++ @patch(+ "products.data_warehouse.backend.presentation.views.external_data_source.trigger_external_data_source_workflow"+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.make_tracked_session")+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth.make_tracked_session"+ )+ def test_setup_custom_oauth2_source_stores_pointer_not_secrets(+ self, mock_token_session, mock_probe_session, _mock_trigger+ ):+ # `setup` validates first and then re-parses the raw payload with the credential gate skipped —+ # the adoption rewrite must be propagated onto that payload, or the created source would keep+ # the raw secrets in job_inputs and orphan the row.+ self._mock_oauth2_network(mock_token_session, mock_probe_session)++ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/setup/",+ data={+ "source_type": "Custom",+ "prefix": "customoauthsetup_",+ "payload": {+ "manifest_json": json.dumps(self._valid_oauth2_manifest()),+ "auth_oauth2_client_secret": "cs",+ "auth_oauth2_refresh_token": "orig-RT",+ },+ },+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ source = ExternalDataSource.objects.get(id=response.json()["id"])+ row = CustomOAuth2Integration.objects.for_team(self.team.pk).get()+ assert source.job_inputs["auth_oauth2_integration_id"] == str(row.pk)+ assert not source.job_inputs.get("auth_oauth2_client_secret")+ assert not source.job_inputs.get("auth_oauth2_refresh_token")+ assert row.external_data_source_id == source.pk++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.make_tracked_session")+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth.make_tracked_session"+ )+ def test_update_reenters_oauth2_secrets_into_bound_row(self, mock_token_session, mock_probe_session):+ # Reconnect happens on the source config screen: re-entered secrets must land in the bound row+ # (not in job_inputs) via the update path's re-serialization.+ self._mock_oauth2_network(mock_token_session, mock_probe_session)+ manifest = self._valid_oauth2_manifest()+ source = ExternalDataSource.objects.create(+ team_id=self.team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ source_type="Custom",+ created_by=self.user,+ prefix="customoauthreconnect_",+ job_inputs={"manifest_json": json.dumps(manifest)},+ )+ row = CustomOAuth2Integration.objects.for_team(self.team.pk).create(+ team=self.team,+ created_by=self.user,+ external_data_source=source,+ config={"client_id": "cid", "token_url": "https://auth.example.com/token", "grant_type": "refresh_token"},+ sensitive_config={"client_secret": "old-cs", "refresh_token": "old-rt"},+ )+ source.job_inputs["auth_oauth2_integration_id"] = str(row.pk)+ source.save(update_fields=["job_inputs"])++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={+ "job_inputs": {+ "manifest_json": json.dumps(manifest),+ "auth_oauth2_client_secret": "new-cs",+ "auth_oauth2_refresh_token": "new-rt",+ }+ },+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ source.refresh_from_db()+ row.refresh_from_db()+ assert source.job_inputs["auth_oauth2_integration_id"] == str(row.pk)+ assert not source.job_inputs.get("auth_oauth2_client_secret")+ assert not source.job_inputs.get("auth_oauth2_refresh_token")+ assert row.sensitive_config["client_secret"] == "new-cs"+ # Validation minted with the re-entered token and persisted the provider's rotation.+ assert mock_token_session.return_value.post.call_args.kwargs["data"]["refresh_token"] == "new-rt"+ assert row.sensitive_config["refresh_token"] == "rotated-RT"++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.CustomSource.validate_credentials",+ return_value=(True, None),+ )+ def test_update_cannot_repoint_oauth2_integration_id(self, _mock_validate_credentials):+ # The pointer is server-managed: an editor submitting a different integration UUID must have it+ # pinned back to the stored one, or they could route another row's credentials to this source.+ source = self._custom_oauth2_integration_source()++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={+ "job_inputs": {"auth_oauth2_integration_id": "33333333-3333-3333-3333-333333333333"},+ },+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ source.refresh_from_db()+ assert source.job_inputs["auth_oauth2_integration_id"] == "11111111-1111-1111-1111-111111111111"+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.CustomSource.validate_credentials",return_value=(True, None),diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.pyindex a0acf05ba78a..af87efa60721 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py@@ -1,5 +1,6 @@import copyimport json+import hashlibimport graphlibfrom collections.abc import Callablefrom datetime import date@@ -695,11 +696,13 @@ class CustomSource(SimpleSource[CustomSourceConfig]):placeholder="",secret=True,),- # Non-secret pointer to a CustomOAuth2Integration row (a UUID). When set, the live+ # Non-secret pointer to a CustomOAuth2Integration row (a UUID). Server-managed: the+ # validation seams write it when adopting the static auth_oauth2_* secrets above into+ # a row, and the API layer drops/pins any client-supplied value. When set, the live# client_secret / refresh_token / minted access token come from that row at sync time- # (so a rotated single-use refresh token gets persisted), and the static auth_oauth2_*- # secrets above are ignored. Not a secret — it's an id, so it doesn't trip the- # credential re-entry gate.+ # (so a rotated single-use refresh token gets persisted), and the static secrets are+ # ignored. Declared here (despite never rendering — the Custom source UI is the+ # manifest builder) so the config codegen keeps it on CustomSourceConfig.SourceFieldInputConfig(name="auth_oauth2_integration_id",label="OAuth2 integration",@@ -780,8 +783,18 @@ class CustomSource(SimpleSource[CustomSourceConfig]):if not ok:return False, err- # An integration-backed OAuth2 source keeps its secrets in the CustomOAuth2Integration row,- # not in job_inputs — `_assemble_manifest` deliberately skipped the static secrets for it. Mint+ # Statically-entered OAuth2 secrets are adopted into a server-managed CustomOAuth2Integration+ # row on every interactive validation, so the durable row — not job_inputs — becomes the home+ # for the client secret and the (possibly rotating) refresh token. The config is rewritten to+ # point at the row with its static secrets cleared; callers that persist the validated config+ # afterwards store the pointer instead of the raw secrets.+ try:+ _adopt_static_oauth2_secrets(manifest, config, team_id, source_id=source_id, owner_user_id=owner_user_id)+ except CustomOAuth2Integration.DoesNotExist:+ return False, OAUTH2_CREDENTIALS_GONE_MESSAGE++ # A row-backed OAuth2 source keeps its secrets in the CustomOAuth2Integration row, not in+ # job_inputs — `_assemble_manifest` deliberately skipped the static secrets for it. Mint# (or reuse a cached token) through the row here, exactly as sync time does, so validation has a# live token to probe with. `get_access_token()` persists a rotated single-use refresh token, so# this is the only seam that re-mints; the data probe below reuses the seeded token via@@ -803,7 +816,7 @@ class CustomSource(SimpleSource[CustomSourceConfig]):owner_user_id=owner_user_id,)except CustomOAuth2Integration.DoesNotExist:- return False, "The linked OAuth2 integration no longer exists. Reconnect the OAuth2 integration."+ return False, OAUTH2_CREDENTIALS_GONE_MESSAGEexcept OAuth2AuthRequestError as exc:auth_config = manifest.get("client", {}).get("auth", {})injected_secrets = tuple(@@ -1019,8 +1032,8 @@ class CustomSource(SimpleSource[CustomSourceConfig]):# message the substring classifier recognises, so without this it would retry until the# activity budget is exhausted. Fail fast like the other deterministic config errors.raise NonRetryableException(- "The OAuth2 integration this source points to no longer exists. "- "Reconnect the OAuth2 integration, then try again."+ "The stored OAuth2 credentials this source points to no longer exist. "+ "Re-enter the client secret and refresh token in the source settings, then try again.") from excexcept ValueError as exc:# A malformed manifest, a missing resource, or a broken parent@@ -1111,7 +1124,16 @@ class CustomSource(SimpleSource[CustomSourceConfig]):if not ok:raise ManifestValidationError(err or "Manifest URL validation failed")- # Integration-backed OAuth2 source: seed the manifest with the row's live secrets + minted token+ # Preview is often the first server-side touch of freshly-typed OAuth2 secrets — adopt them+ # into a (still unbound) integration row before minting, so a provider that rotates single-use+ # refresh tokens rotates against a persisted row rather than a throwaway in-memory auth. The+ # source-create that follows reuses the same row via _reusable_unbound_integration.+ try:+ _adopt_static_oauth2_secrets(manifest, config, team_id, source_id=None, owner_user_id=owner_user_id)+ except CustomOAuth2Integration.DoesNotExist as exc:+ raise ManifestValidationError(OAUTH2_CREDENTIALS_GONE_MESSAGE) from exc++ # Row-backed OAuth2 source: seed the manifest with the row's live secrets + minted token# (mint-or-reuse, persisting any rotation) so the preview's lazy first-request mint reuses the# seeded token instead of re-minting on the throwaway preview auth — which would rotate the# single-use refresh token without writing it back. Same seam as sync time / validate_credentials.@@ -1123,9 +1145,7 @@ class CustomSource(SimpleSource[CustomSourceConfig]):manifest, config.auth_oauth2_integration_id, team_id, forbid_bound=True, owner_user_id=owner_user_id)except CustomOAuth2Integration.DoesNotExist as exc:- raise ManifestValidationError(- "The linked OAuth2 integration no longer exists. Reconnect the OAuth2 integration."- ) from exc+ raise ManifestValidationError(OAUTH2_CREDENTIALS_GONE_MESSAGE) from excexcept OAuth2AuthRequestError as exc:# The mint is a live network call, so a token-endpoint failure here is a fetch-style# error, not a config error — surface it the same way a row-read failure would be, with@@ -1447,6 +1467,171 @@ def _inject_auth_secrets(manifest: dict[str, Any], config: CustomSourceConfig) -auth["refresh_token"] = config.auth_oauth2_refresh_token+# The exact non-secret OAuth2Auth knobs a manifest's `client.auth` may declare — the schema of a+# CustomOAuth2Integration row's `config` (plus the worker-written `refreshed_at`).+_OAUTH2_ROW_CONFIG_KEYS = (+ "client_id",+ "token_url",+ "grant_type",+ "scopes",+ "access_token_name",+ "expires_in_name",+ "expiry_date_format",+ "extra_token_request_params",+ "token_request_headers",+ "client_auth_method",+)++# User-facing copy for a row-backed source whose integration row no longer resolves. Recovery is+# always the same: re-enter the client secret / refresh token in the source's settings, which adopts+# them into a fresh row.+OAUTH2_CREDENTIALS_GONE_MESSAGE = (+ "This source's stored OAuth2 credentials are no longer available. "+ "Re-enter the client secret and refresh token in the source settings to reconnect."+)+++def _oauth2_row_config(auth: dict[str, Any]) -> dict[str, Any]:+ """The non-secret OAuth2 client config a manifest declares, in row-`config` shape.++ The grant is normalized to its default so row matching doesn't split on an+ implied-vs-explicit ``client_credentials``.+ """+ row_config = {key: auth[key] for key in _OAUTH2_ROW_CONFIG_KEYS if auth.get(key) not in (None, "")}+ row_config["grant_type"] = auth.get("grant_type") or "client_credentials"+ return row_config+++def _reusable_unbound_integration(+ team_id: int, owner_user_id: int, row_config: dict[str, Any]+) -> Optional[CustomOAuth2Integration]:+ """The caller's own unbound integration row for the same OAuth2 client, if one exists.++ An unbound row is left behind by a preview or a failed create attempt — and may hold a rotated+ refresh token the user never saw, which is exactly why it must be reused rather than recreated:+ for providers that rotate single-use refresh tokens, the row's token is the only live descendant+ of the one the user typed. Newest first so retries converge on the most recently touched row.+ """+ candidates = (+ CustomOAuth2Integration.objects.for_team(team_id)+ .filter(external_data_source__isnull=True, created_by_id=owner_user_id)+ .order_by("-created_at")+ )+ for candidate in candidates:+ if all(candidate.config.get(key) == row_config.get(key) for key in ("client_id", "token_url", "grant_type")):+ return candidate+ return None+++def _apply_oauth2_material(+ integration: CustomOAuth2Integration, row_config: dict[str, Any], config: CustomSourceConfig+) -> None:+ """Sync the manifest's non-secret OAuth2 config and any re-entered secrets onto the row.++ A re-entered refresh token only replaces the stored one when it differs from the last token the+ user submitted (tracked by fingerprint) *and* the non-secret client config is unchanged:+ re-typing the original token — already consumed by a rotating provider — must not clobber the+ rotated descendant the row persisted across a retry or preview→create. But once the config+ changes (a repointed token_url above all), the keep-rule must not apply: it would mint the live+ rotated token — a credential the editor never possessed — against the new destination. Replacing+ with the typed token means a config change only ever sends material the editor provably knows.+ A replacement (or a config change) drops the cached access token so the next mint uses the new+ material instead of riding a token minted under the old one.+ """+ sensitive = dict(integration.sensitive_config)+ new_config = dict(row_config)+ if "refreshed_at" in integration.config:+ new_config["refreshed_at"] = integration.config["refreshed_at"]+ config_changed = new_config != integration.config+ if config_changed:+ sensitive.pop("access_token", None)+ sensitive.pop("token_expiry", None)+ if config.auth_oauth2_client_secret:+ sensitive["client_secret"] = config.auth_oauth2_client_secret+ if config.auth_oauth2_refresh_token:+ fingerprint = hashlib.sha256(config.auth_oauth2_refresh_token.encode()).hexdigest()+ if config_changed or fingerprint != sensitive.get("refresh_token_fingerprint"):+ sensitive["refresh_token"] = config.auth_oauth2_refresh_token+ sensitive["refresh_token_fingerprint"] = fingerprint+ sensitive.pop("access_token", None)+ sensitive.pop("token_expiry", None)+ if config_changed or sensitive != integration.sensitive_config:+ integration.config = new_config+ integration.sensitive_config = sensitive+ integration.save(update_fields=["config", "sensitive_config"])+++def _adopt_static_oauth2_secrets(+ manifest: dict[str, Any],+ config: CustomSourceConfig,+ team_id: int,+ *,+ source_id: Optional[str],+ owner_user_id: Optional[int],+) -> None:+ """Move statically-entered OAuth2 secrets into a server-managed CustomOAuth2Integration row.++ The custom source config screen only ever collects the non-secret client config (in the manifest)+ plus the client secret / refresh token as static secret fields; the durable integration row is an+ implementation detail created here, with no user-facing API. Runs only on interactive request+ seams (``owner_user_id`` set): create/update validation, schema discovery, and preview. Mutates+ ``config`` — pointing it at the row and clearing the static secrets — and scrubs the secrets from+ the assembled ``manifest``, so a caller that persists the config afterwards stores a secret-free+ ``job_inputs``.++ * No row linked yet: reuse the caller's unbound row for the same client (see+ :func:`_reusable_unbound_integration`), else create one.+ * Row already linked (``config.auth_oauth2_integration_id``): authorize it for this source first —+ an unauthorized caller must not be able to rewrite another source's row config — then refresh+ its non-secret config from the manifest and rotate in any re-entered secrets (the reconnect+ path).++ Raises ``CustomOAuth2Integration.DoesNotExist`` when the linked row is not usable by this+ source/owner, or when it is gone and no re-entered secrets are available to rebuild it from.+ """+ if owner_user_id is None:+ return+ client = manifest.get("client")+ if not isinstance(client, dict):+ return+ auth = client.get("auth")+ if not isinstance(auth, dict) or auth.get("type") != "oauth2":+ return+ has_static_secrets = bool(config.auth_oauth2_client_secret or config.auth_oauth2_refresh_token)+ if not config.auth_oauth2_integration_id and not has_static_secrets:+ return++ row_config = _oauth2_row_config(auth)+ integration: Optional[CustomOAuth2Integration] = None+ if config.auth_oauth2_integration_id:+ try:+ integration = get_custom_oauth2_integration(config.auth_oauth2_integration_id, team_id)+ except CustomOAuth2Integration.DoesNotExist:+ # Dangling pointer (row deleted). Re-entered secrets are the recovery path: fall through+ # and adopt them into a fresh row instead of leaving the source stuck on a dead pointer.+ if not has_static_secrets:+ raise+ if integration is not None:+ _authorize_integration_for_source(+ integration, team_id, source_id=source_id, forbid_bound=source_id is None, owner_user_id=owner_user_id+ )+ if integration is None:+ integration = _reusable_unbound_integration(team_id, owner_user_id, row_config) or (+ CustomOAuth2Integration.objects.for_team(team_id).create(+ team_id=team_id, created_by_id=owner_user_id, config=row_config+ )+ )+ _apply_oauth2_material(integration, row_config, config)++ config.auth_oauth2_integration_id = str(integration.id)+ config.auth_oauth2_client_secret = None+ config.auth_oauth2_refresh_token = None+ # The static secrets were already copied into the manifest by _inject_auth_secrets — scrub them so+ # only the row-minted token (seeded by _inject_oauth2_integration_secrets) ever reaches the engine.+ auth.pop("client_secret", None)+ auth.pop("refresh_token", None)++def _authorize_integration_for_source(integration: CustomOAuth2Integration,team_id: int,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.pyindex 8815ee556c23..2300b031f7b1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py@@ -1,6 +1,7 @@import ioimport gzipimport json+import hashlibfrom datetime import UTC, datetime, timedeltafrom typing import Any, castfrom urllib.parse import quote@@ -652,7 +653,7 @@ class TestCustomSourceOAuth2IntegrationWiring(BaseTest):ok, err = CustomSource().validate_credentials(config, team_id=self.team.pk)assert not ok- assert "no longer exists" in (err or "")+ assert "no longer available" in (err or "")@patch(f"{AUTH_MODULE}.make_tracked_session")def test_validate_credentials_on_update_rejects_another_sources_integration(self, mock_session):@@ -669,7 +670,7 @@ class TestCustomSourceOAuth2IntegrationWiring(BaseTest):ok, err = CustomSource().validate_credentials(config, team_id=self.team.pk, source_id=str(attacker.pk))assert not ok- assert "no longer exists" in (err or "")+ assert "no longer available" in (err or "")mock_session.return_value.post.assert_not_called()@patch(f"{AUTH_MODULE}.make_tracked_session")@@ -686,7 +687,7 @@ class TestCustomSourceOAuth2IntegrationWiring(BaseTest):ok, err = CustomSource().validate_credentials(config, team_id=self.team.pk)assert not ok- assert "no longer exists" in (err or "")+ assert "no longer available" in (err or "")mock_session.return_value.post.assert_not_called()@patch(f"{AUTH_MODULE}.make_tracked_session")@@ -778,6 +779,217 @@ class TestCustomSourceOAuth2IntegrationWiring(BaseTest):assert manifest["client"]["auth"]["access_token"] == "minted-AT"+class TestCustomSourceOAuth2SecretAdoption(BaseTest):+ def _oauth2_manifest(self, token_url: str = "https://auth.example.com/token") -> dict:+ manifest = _minimal_manifest()+ manifest["client"]["auth"] = {+ "type": "oauth2",+ "client_id": "cid",+ "token_url": token_url,+ "grant_type": "refresh_token",+ }+ return manifest++ def _static_config(self, **overrides) -> CustomSourceConfig:+ params = {+ "manifest_json": json.dumps(self._oauth2_manifest()),+ "auth_oauth2_client_secret": "cs",+ "auth_oauth2_refresh_token": "orig-RT",+ **overrides,+ }+ return CustomSourceConfig(**params)++ def _make_source(self, name: str = "a") -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team=self.team,+ source_id=f"sid-{name}",+ connection_id=f"cid-{name}",+ status="Completed",+ source_type="Custom",+ )++ def _mock_mint(self, mock_token_session, mock_probe_session, rotated: str = "rotated-RT") -> None:+ mock_token_session.return_value.post.return_value = _token_response(+ payload={"access_token": "minted-AT", "expires_in": 3600, "refresh_token": rotated}+ )+ mock_probe_session.return_value.request.return_value = MagicMock(status_code=200, text="{}")++ @patch(SOURCE_MODULE)+ @patch(f"{AUTH_MODULE}.make_tracked_session")+ def test_create_validation_adopts_static_secrets_into_row(self, mock_token_session, mock_probe_session):+ # The current-UI flow: static secrets typed on the source config screen are adopted into a+ # server-managed row during create validation, the config is rewritten to point at it (so the+ # persisted job_inputs never carry the raw secrets), and the mint happens through the row so+ # the rotated single-use refresh token is durably persisted.+ self._mock_mint(mock_token_session, mock_probe_session)+ config = self._static_config()++ ok, err = CustomSource().validate_credentials(config, team_id=self.team.pk, owner_user_id=self.user.pk)++ assert ok, err+ row = CustomOAuth2Integration.objects.for_team(self.team.pk).get()+ assert config.auth_oauth2_integration_id == str(row.pk)+ assert config.auth_oauth2_client_secret is None+ assert config.auth_oauth2_refresh_token is None+ assert row.external_data_source_id is None+ assert row.created_by_id == self.user.pk+ assert row.config["client_id"] == "cid"+ assert row.config["token_url"] == "https://auth.example.com/token"+ assert row.sensitive_config["client_secret"] == "cs"+ assert row.sensitive_config["refresh_token"] == "rotated-RT"++ @patch(SOURCE_MODULE)+ @patch(f"{AUTH_MODULE}.make_tracked_session")+ def test_retry_reuses_unbound_row_and_mints_from_rotated_token(self, mock_token_session, mock_probe_session):+ # Preview-then-create (and failed-create retry) continuity for rotating providers: the second+ # validation re-submits the same original refresh token, which the provider already consumed.+ # It must match the caller's unbound row by client config and mint from the row's rotated+ # descendant — a fresh row (or a fingerprint miss overwriting the rotation) would mint from the+ # consumed original and fail with invalid_grant. The second call runs past the first token's+ # expiry, or the row would just reuse the still-valid cached access token without minting.+ self._mock_mint(mock_token_session, mock_probe_session, rotated="rotated-RT-1")+ first_config = self._static_config()+ with freeze_time("2025-01-01T00:00:00Z"):+ ok, err = CustomSource().validate_credentials(+ first_config, team_id=self.team.pk, owner_user_id=self.user.pk+ )+ assert ok, err++ self._mock_mint(mock_token_session, mock_probe_session, rotated="rotated-RT-2")+ second_config = self._static_config()+ with freeze_time("2025-01-01T02:00:00Z"):+ ok, err = CustomSource().validate_credentials(+ second_config, team_id=self.team.pk, owner_user_id=self.user.pk+ )++ assert ok, err+ assert second_config.auth_oauth2_integration_id == first_config.auth_oauth2_integration_id+ row = CustomOAuth2Integration.objects.for_team(self.team.pk).get()+ assert mock_token_session.return_value.post.call_args.kwargs["data"]["refresh_token"] == "rotated-RT-1"+ assert row.sensitive_config["refresh_token"] == "rotated-RT-2"++ @patch(SOURCE_MODULE)+ @patch(f"{AUTH_MODULE}.make_tracked_session")+ def test_newly_supplied_refresh_token_replaces_stored_one(self, mock_token_session, mock_probe_session):+ # A deliberately different refresh token (the recovery for a revoked grant) must replace the+ # stored rotation lineage — the fingerprint keep-rule only applies to a re-typed original.+ self._mock_mint(mock_token_session, mock_probe_session, rotated="rotated-RT-1")+ ok, err = CustomSource().validate_credentials(+ self._static_config(), team_id=self.team.pk, owner_user_id=self.user.pk+ )+ assert ok, err++ self._mock_mint(mock_token_session, mock_probe_session, rotated="rotated-RT-2")+ config = self._static_config(auth_oauth2_refresh_token="brand-new-RT")+ ok, err = CustomSource().validate_credentials(config, team_id=self.team.pk, owner_user_id=self.user.pk)++ assert ok, err+ assert mock_token_session.return_value.post.call_args.kwargs["data"]["refresh_token"] == "brand-new-RT"+ assert CustomOAuth2Integration.objects.for_team(self.team.pk).count() == 1++ @patch(SOURCE_MODULE)+ @patch(f"{AUTH_MODULE}.make_tracked_session")+ def test_adoption_never_reuses_another_users_unbound_row(self, mock_token_session, mock_probe_session):+ # An unbound row is a floating credential scoped to its creator: a teammate submitting the same+ # client config must get their own row, not adopt (and mint through) someone else's.+ self._mock_mint(mock_token_session, mock_probe_session)+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)+ foreign = CustomOAuth2Integration.objects.for_team(self.team.pk).create(+ team=self.team,+ created_by=other_user,+ config={"client_id": "cid", "token_url": "https://auth.example.com/token", "grant_type": "refresh_token"},+ sensitive_config={"client_secret": "foreign-cs", "refresh_token": "foreign-RT"},+ )+ config = self._static_config()++ ok, err = CustomSource().validate_credentials(config, team_id=self.team.pk, owner_user_id=self.user.pk)++ assert ok, err+ assert config.auth_oauth2_integration_id != str(foreign.pk)+ foreign.refresh_from_db()+ assert foreign.sensitive_config["refresh_token"] == "foreign-RT"+ assert CustomOAuth2Integration.objects.for_team(self.team.pk).count() == 2++ @patch(SOURCE_MODULE)+ @patch(f"{AUTH_MODULE}.make_tracked_session")+ def test_token_url_change_never_mints_the_rotated_token(self, mock_token_session, mock_probe_session):+ # An editor re-typing the consumed original token while repointing token_url must not get the+ # live rotated descendant — a credential they never possessed — minted against the new host.+ # The fingerprint keep-rule is suspended on a config change, so the mint carries only the+ # token the editor typed.+ self._mock_mint(mock_token_session, mock_probe_session)+ source = self._make_source("repointed")+ row = CustomOAuth2Integration.objects.for_team(self.team.pk).create(+ team=self.team,+ created_by=self.user,+ external_data_source=source,+ config={"client_id": "cid", "token_url": "https://auth.example.com/token", "grant_type": "refresh_token"},+ sensitive_config={+ "client_secret": "cs",+ "refresh_token": "live-rotated-RT",+ "refresh_token_fingerprint": hashlib.sha256(b"orig-RT").hexdigest(),+ },+ )+ config = self._static_config(+ manifest_json=json.dumps(self._oauth2_manifest(token_url="https://editor-controlled.example.net/token")),+ auth_oauth2_integration_id=str(row.pk),+ )++ ok, err = CustomSource().validate_credentials(+ config, team_id=self.team.pk, source_id=str(source.pk), owner_user_id=self.user.pk+ )++ assert ok, err+ minted_with = mock_token_session.return_value.post.call_args+ assert minted_with.args[0] == "https://editor-controlled.example.net/token"+ assert minted_with.kwargs["data"]["refresh_token"] == "orig-RT"+ assert "live-rotated-RT" not in str(minted_with)++ @patch(f"{AUTH_MODULE}.make_tracked_session")+ def test_foreign_pointer_is_rejected_before_any_row_mutation(self, mock_session):+ # Adoption refreshes a linked row's config from the submitted manifest — so authorization must+ # come first, or a create-seam caller pointing at another source's row could rewrite its+ # token_url (redirecting the next mint, with the stored client_secret, to an attacker host).+ victim_source = self._make_source("victim")+ victim_row = CustomOAuth2Integration.objects.for_team(self.team.pk).create(+ team=self.team,+ external_data_source=victim_source,+ config={"client_id": "cid", "token_url": "https://auth.example.com/token", "grant_type": "refresh_token"},+ sensitive_config={"client_secret": "cs", "refresh_token": "rt"},+ )+ config = self._static_config(+ manifest_json=json.dumps(self._oauth2_manifest(token_url="https://attacker.example.net/token")),+ auth_oauth2_integration_id=str(victim_row.pk),+ )++ ok, err = CustomSource().validate_credentials(config, team_id=self.team.pk, owner_user_id=self.user.pk)++ assert not ok+ victim_row.refresh_from_db()+ assert victim_row.config["token_url"] == "https://auth.example.com/token"+ assert victim_row.sensitive_config["client_secret"] == "cs"+ mock_session.return_value.post.assert_not_called()++ @patch(SOURCE_MODULE)+ @patch(f"{AUTH_MODULE}.make_tracked_session")+ def test_update_with_dangling_pointer_recovers_via_reentered_secrets(self, mock_token_session, mock_probe_session):+ # A source whose row was deleted must not be stuck on the dead pointer forever: re-entering the+ # secrets on the config screen adopts them into a fresh row bound to the source.+ self._mock_mint(mock_token_session, mock_probe_session)+ source = self._make_source("orphaned")+ config = self._static_config(auth_oauth2_integration_id="11111111-1111-1111-1111-111111111111")++ ok, err = CustomSource().validate_credentials(+ config, team_id=self.team.pk, source_id=str(source.pk), owner_user_id=self.user.pk+ )++ assert ok, err+ row = CustomOAuth2Integration.objects.for_team(self.team.pk).get()+ assert config.auth_oauth2_integration_id == str(row.pk)+ assert str(row.external_data_source_id) == str(source.pk)+ assert row.sensitive_config["client_secret"] == "cs"++class TestCustomSourceGetSchemas(SimpleTestCase):def test_returns_one_schema_per_resource(self):manifest = _minimal_manifest()