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(warehouse-sources): wire custom source OAuth2 to the integration store (#66791)

Marcus Hofb6472997d355
diff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.py
index 7fa33a45e13c..0cf28ec6976f 100644
--- a/products/data_warehouse/backend/presentation/views/external_data_source.py
+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py
@@ -106,6 +106,7 @@ from products.warehouse_sources.backend.facade.api import (
validate_source_prefix,
)
from products.warehouse_sources.backend.facade.models import (
+ CustomOAuth2Integration,
DataWarehouseTable,
ExternalDataJob,
ExternalDataSchema,
@@ -946,9 +947,29 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
existing_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
+ )
+
if connection_host_changed or ssh_tunnel_changed or manifest_host_added:
gate_sensitive_fields = sensitive_fields - _CREATION_ONLY_SECRET_FIELDS
- if has_preserved_credentials(existing_job_inputs, incoming_job_inputs, gate_sensitive_fields):
+ preserved_credentials = has_preserved_credentials(
+ existing_job_inputs, incoming_job_inputs, gate_sensitive_fields
+ )
+ if preserved_credentials or preserved_oauth2_integration:
if ssh_tunnel_changed:
raise ValidationError("Changing the SSH tunnel requires re-entering your database credentials.")
if manifest_host_added:
@@ -1043,6 +1064,17 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
credentials_valid, credentials_error = source.validate_credentials_for_access_method(
cast(Any, source_config), instance.team_id, instance.access_method
)
+ elif isinstance(source, CustomSource):
+ # Pass the source being updated so an integration-backed OAuth2 source can only validate
+ # with the integration bound to it — not another source's, whose token the probe would
+ # otherwise mint and send to the submitted manifest host. owner_user_id additionally gates
+ # an as-yet-unbound integration to its creator.
+ credentials_valid, credentials_error = source.validate_credentials(
+ source_config,
+ instance.team_id,
+ source_id=str(instance.pk),
+ owner_user_id=self.context["request"].user.id,
+ )
else:
credentials_valid, credentials_error = source.validate_credentials(source_config, instance.team_id)
if not credentials_valid:
@@ -2569,6 +2601,13 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
credentials_valid, credentials_error = source.validate_credentials_for_access_method(
cast(Any, source_config), self.team_id, access_method
)
+ elif isinstance(source, CustomSource):
+ # Schema discovery for an as-yet-uncreated source: an integration-backed manifest may only use
+ # an unbound integration owned by the requester, or the probe could send another source's token
+ # to the submitted host.
+ credentials_valid, credentials_error = source.validate_credentials(
+ source_config, self.team_id, owner_user_id=self.request.user.id
+ )
else:
credentials_valid, credentials_error = source.validate_credentials(source_config, self.team_id)
if not credentials_valid:
@@ -2776,6 +2815,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
self.team_id,
serializer.validated_data["resource_name"],
serializer.validated_data["limit"],
+ owner_user_id=self.request.user.id,
)
except ValueError as e:
# ManifestValidationError (a ValueError) for manifest/graph/URL issues, or a plain
@@ -2981,6 +3021,12 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
credentials_valid, credentials_error = source.validate_credentials_for_access_method(
cast(Any, source_config), self.team_id, access_method
)
+ elif isinstance(source, CustomSource):
+ # Create-time validation for an integration-backed manifest may only use an unbound integration
+ # owned by the requester, so the probe can't send another source's token to the submitted host.
+ credentials_valid, credentials_error = source.validate_credentials(
+ source_config, self.team_id, owner_user_id=self.request.user.id
+ )
else:
credentials_valid, credentials_error = source.validate_credentials(source_config, self.team_id)
if not credentials_valid:
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.py
index 086788dc8d6a..b15ac9eb81c1 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
@@ -44,6 +44,7 @@ from products.data_warehouse.backend.presentation.views.external_data_source imp
)
from products.revenue_analytics.backend.joins import get_customer_revenue_view_name
from products.warehouse_sources.backend.facade.models import (
+ CustomOAuth2Integration,
DataWarehouseTable,
ExternalDataJob,
ExternalDataSchema,
@@ -5224,6 +5225,94 @@ class TestExternalDataSource(APIBaseTest):
# The credential probe only runs once the re-entry gate has passed.
assert mock_validate_credentials.called == (expected_status == 200)
+ def _custom_oauth2_integration_source(self) -> ExternalDataSource:
+ manifest = {
+ "client": {
+ "base_url": "https://api.example.com",
+ "auth": {"type": "oauth2", "client_id": "cid", "token_url": "https://auth.example.com/token"},
+ },
+ "resources": [{"name": "users", "endpoint": {"path": "/users"}}],
+ }
+ return 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="custom_oauth2_int",
+ job_inputs={
+ "manifest_json": json.dumps(manifest),
+ "auth_oauth2_integration_id": "11111111-1111-1111-1111-111111111111",
+ },
+ )
+
+ @parameterized.expand(
+ [("preserved_integration", {}, 400), ("cleared_integration", {"auth_oauth2_integration_id": ""}, 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(
+ 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.
+ source = self._custom_oauth2_integration_source()
+ new_manifest = {
+ "client": {
+ "base_url": "https://attacker.example.net",
+ "auth": {"type": "oauth2", "client_id": "cid", "token_url": "https://auth.example.com/token"},
+ },
+ "resources": [{"name": "users", "endpoint": {"path": "/users"}}],
+ }
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
+ data={"job_inputs": {"manifest_json": json.dumps(new_manifest), **extra_inputs}},
+ )
+
+ assert response.status_code == expected_status, response.json()
+ assert ("re-entering your credentials" in str(response.json())) == (expected_status == 400)
+ assert mock_validate_credentials.called == (expected_status == 200)
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.CustomSource.validate_credentials",
+ return_value=(True, None),
+ )
+ def test_update_custom_oauth2_source_cannot_clear_pointer_to_move_host_while_bound(self, mock_validate_credentials):
+ # Bypass guard: clearing auth_oauth2_integration_id does not unbind the CustomOAuth2Integration row,
+ # so an editor must not be able to clear the pointer, move the manifest host, then re-add the pointer
+ # to redirect the still-bound token. A row bound to the source makes the host-change gate fire even
+ # when job_inputs currently omits the pointer.
+ 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": "s"},
+ )
+ new_manifest = {
+ "client": {
+ "base_url": "https://attacker.example.net",
+ "auth": {"type": "oauth2", "client_id": "cid", "token_url": "https://auth.example.com/token"},
+ },
+ "resources": [{"name": "users", "endpoint": {"path": "/users"}}],
+ }
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
+ data={"job_inputs": {"manifest_json": json.dumps(new_manifest), "auth_oauth2_integration_id": ""}},
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "re-entering your credentials" in str(response.json())
+ mock_validate_credentials.assert_not_called()
+
@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/models/custom_oauth2_integration.py b/products/warehouse_sources/backend/models/custom_oauth2_integration.py
index 18325124ccc9..8791fc99035b 100644
--- a/products/warehouse_sources/backend/models/custom_oauth2_integration.py
+++ b/products/warehouse_sources/backend/models/custom_oauth2_integration.py
@@ -125,18 +125,18 @@ class CustomOAuth2Integration(TeamScopedRootMixin, CreatedMetaFields, UpdatedMet
if not expiry:
return True
token_expiry = datetime.fromisoformat(expiry)
- # Cap the buffer at half the token's lifetime, matching OAuth2Auth._is_token_expired: a token
- # whose whole TTL is <= the buffer would otherwise read as already-expired the instant it's
- # minted, forcing a re-mint on every call. lifetime is derived from the data we already store —
- # the absolute expiry and the mint timestamp (`refreshed_at`, unix seconds). When there's no
- # mint timestamp the lifetime is unknown, so fall back to the flat buffer.
+ # Refresh proactively at the halfway point of the token's lifetime, mirroring
+ # OauthIntegration.access_token_expired (`expires_in / 2`). The engine no longer refreshes
+ # mid-sync (integration-backed sources seed a static bearer with manages_own_token=False), so this
+ # up-front refresh is the only one — refreshing at the midpoint gives each sync ample runway
+ # instead of handing over a token that's seconds from expiry. lifetime is derived from the data
+ # we already store: the absolute expiry and the mint timestamp (`refreshed_at`, unix seconds).
+ # With no mint timestamp the lifetime is unknown, so fall back to a flat buffer before expiry.
refreshed_at = self.config.get("refreshed_at")
if refreshed_at is None:
- buffer = _TOKEN_EXPIRY_BUFFER
- else:
- lifetime = token_expiry - datetime.fromtimestamp(refreshed_at, UTC)
- buffer = min(_TOKEN_EXPIRY_BUFFER, max(lifetime / 2, timedelta(0)))
- return datetime.now(UTC) >= token_expiry - buffer
+ return datetime.now(UTC) >= token_expiry - _TOKEN_EXPIRY_BUFFER
+ lifetime = token_expiry - datetime.fromtimestamp(refreshed_at, UTC)
+ return datetime.now(UTC) >= token_expiry - max(lifetime / 2, timedelta(0))
def get_access_token(self) -> str:
"""Reuse the stored token while it's valid; refresh + persist only when expired.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/auth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/auth.py
index f44f56c62935..b79b143b4382 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/auth.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/auth.py
@@ -164,6 +164,7 @@ class OAuth2Auth(BearerTokenAuth):
extra_token_request_params: Optional[dict[str, str]] = None,
token_request_headers: Optional[dict[str, str]] = None,
client_auth_method: OAuth2ClientAuthMethod = "body",
+ manages_own_token: bool = True,
) -> None:
super().__init__(token=access_token)
self.token_url = token_url
@@ -178,12 +179,17 @@ class OAuth2Auth(BearerTokenAuth):
self.extra_token_request_params = extra_token_request_params
self.token_request_headers = token_request_headers
self.client_auth_method = client_auth_method
+ # False for an integration-backed source: it mints + persists its token up front (under a row
+ # lock) and hands this auth a ready bearer, so the engine must never mint. A mid-sync re-mint
+ # would consume a single-use refresh token whose rotation this in-memory auth can't persist,
+ # permanently orphaning the integration. See __call__.
+ self.manages_own_token = manages_own_token
# A rotating provider returns a fresh single-use refresh token alongside each access token;
# captured here (never overwriting self.refresh_token, which must keep minting this run) so a
# caller holding a DB row can persist it for the next sync. None until a rotation is seen.
self.rotated_refresh_token: Optional[str] = None
- # None => mint on the first request. A pre-supplied access_token (rare; never
- # set for custom sources today) has no known expiry, so it too re-mints first.
+ # None => mint on the first request. A pre-supplied access_token (rare; never set for custom
+ # sources today) has no known expiry, so it too re-mints first.
self.token_expiry: Optional[datetime] = None
# When the current token was minted — used to cap the refresh buffer at half the
# token's lifetime so a very short-lived token isn't treated as expired the instant
@@ -191,7 +197,11 @@ class OAuth2Auth(BearerTokenAuth):
self._minted_at: Optional[datetime] = None
def __call__(self, request: PreparedRequest) -> PreparedRequest:
- if self.token is None or self._is_token_expired():
+ # An externally managed token (manages_own_token=False, the integration path) was minted +
+ # persisted up front, so never mint here. Send the token; if it has expired the resource server
+ # returns a 401 — a retryable failure whose retry re-mints up front through the row, so a
+ # single-use refresh token is never consumed inside the engine and can't be lost.
+ if self.manages_own_token and (self.token is None or self._is_token_expired()):
self._obtain_token()
# The minted token must stay on the `Authorization` header. At sync time the tracked
# session fixes its value-based redaction set at construction — before this lazy mint —
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_auth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_auth.py
index 3282e3a29e4a..c45390ce4cda 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_auth.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_auth.py
@@ -57,6 +57,25 @@ class TestOAuth2Auth(SimpleTestCase):
# No refresh_token in the response → nothing to write back.
assert auth.rotated_refresh_token is None
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_externally_managed_token_never_mints_even_when_expired(self, mock_session):
+ # A single-use refresh token rotates only once, so an integration-backed source seeds a static
+ # bearer with manages_own_token=False: the engine must never re-mint. Even with no known expiry
+ # (so _is_token_expired() reads True), __call__ sends the seeded token as-is (the resource server
+ # 401s — a retryable failure whose retry re-mints up front through the row) instead of consuming
+ # and losing the rotation.
+ auth = OAuth2Auth(
+ token_url="https://auth.example.com/token",
+ client_id="cid",
+ client_secret="cs",
+ grant_type="refresh_token",
+ refresh_token="orig-RT",
+ access_token="seeded-AT",
+ manages_own_token=False,
+ )
+ assert _apply_auth(auth) == "Bearer seeded-AT"
+ mock_session.return_value.post.assert_not_called()
+
@patch(f"{AUTH_MODULE}.make_tracked_session")
def test_refresh_token_grant_body_and_no_in_memory_rotation(self, mock_session):
mock_session.return_value.post.return_value = _token_response(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py
index 1e2dcdc6f901..15670694907d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py
@@ -136,6 +136,9 @@ class OAuth2AuthConfig(AuthTypeConfig, total=False):
extra_token_request_params: Optional[dict[str, str]]
token_request_headers: Optional[dict[str, str]]
client_auth_method: Optional[OAuth2ClientAuthMethod]
+ manages_own_token: Optional[
+ bool
+ ] # False from integration injection: token is minted+persisted up front, so the engine must never mint
AuthConfig = (
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.py
index a2fc3af70e9b..a0acf05ba78a 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
@@ -6,6 +6,8 @@ from datetime import date
from typing import Any, Literal, NamedTuple, Optional, cast
from urllib.parse import quote, quote_plus, urlparse
+from django.db import IntegrityError
+
import structlog
from jsonpath_ng.exceptions import JSONPathError
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
@@ -23,6 +25,10 @@ from posthog.schema import (
from posthog.cloud_utils import is_cloud
+from products.warehouse_sources.backend.models.custom_oauth2_integration import (
+ CustomOAuth2Integration,
+ get_custom_oauth2_integration,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
SortMode,
SourceInputs,
@@ -689,6 +695,19 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
placeholder="",
secret=True,
),
+ # Non-secret pointer to a CustomOAuth2Integration row (a UUID). 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.
+ SourceFieldInputConfig(
+ name="auth_oauth2_integration_id",
+ label="OAuth2 integration",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="",
+ secret=False,
+ ),
],
),
)
@@ -735,7 +754,13 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
return manifest
def validate_credentials(
- self, config: CustomSourceConfig, team_id: int, schema_name: Optional[str] = None
+ self,
+ config: CustomSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ *,
+ source_id: Optional[str] = None,
+ owner_user_id: Optional[int] = None,
) -> tuple[bool, str | None]:
try:
manifest = self._assemble_manifest(config)
@@ -755,6 +780,45 @@ 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
+ # (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
+ # `OAuth2Auth.__call__` and must NOT re-mint (that would rotate without writeback — see the guard
+ # on the pre-mint block). Errors mirror the pre-mint handling: a permanent token rejection blocks
+ # with a pointed message; a transient one doesn't block (the first real sync retries).
+ if config.auth_oauth2_integration_id:
+ try:
+ # Bind the integration to the source being validated, mirroring sync/preview: on update
+ # (source_id given) the row must belong to that source; on create/setup (no source yet) it
+ # must be unbound. Without this, the probe below could mint and send another source's token
+ # to an attacker-supplied base_url.
+ _inject_oauth2_integration_secrets(
+ manifest,
+ config.auth_oauth2_integration_id,
+ team_id,
+ source_id=source_id,
+ forbid_bound=source_id is None,
+ owner_user_id=owner_user_id,
+ )
+ except CustomOAuth2Integration.DoesNotExist:
+ return False, "The linked OAuth2 integration no longer exists. Reconnect the OAuth2 integration."
+ except OAuth2AuthRequestError as exc:
+ auth_config = manifest.get("client", {}).get("auth", {})
+ injected_secrets = tuple(
+ str(auth_config[key])
+ for key in ("client_secret", "refresh_token", "access_token")
+ if auth_config.get(key)
+ )
+ if exc.is_permanent:
+ return False, _redact_secrets(
+ f"The OAuth2 token endpoint rejected the request: {strip_oauth2_permanent_marker(str(exc))}",
+ injected_secrets,
+ )
+ # Transient (429 / 5xx): don't block creation — the first real sync retries the mint.
+ return True, None
+
# Probe a small prefix of resources so we surface auth/connection errors
# at create-time rather than waiting for the first sync. The auth/header
# setup comes from the shared client config, so it is built once and
@@ -780,7 +844,13 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
# freshly-minted access token join that session's redaction set. A transient
# (429 / 5xx) token error must not block creation — the first real sync retries —
# so only a permanent error (invalid_client / invalid_grant / other 4xx) is surfaced.
- if isinstance(probe_auth, OAuth2Auth):
+ #
+ # Skip this for an integration-backed source: its token was already minted+persisted above
+ # (via the row's writeback-safe path) and seeded into the manifest. Re-minting on this
+ # throwaway `probe_auth` would rotate the single-use refresh token WITHOUT persisting it,
+ # orphaning the row on a consumed token. The seeded token reaches the probe through
+ # `OAuth2Auth.__call__`, which doesn't re-mint a still-valid token.
+ if isinstance(probe_auth, OAuth2Auth) and not config.auth_oauth2_integration_id:
try:
# Bound the inline token exchange to the same budget as the data probe — this runs
# on the API request thread, so a stalled token endpoint must fail fast (well within
@@ -901,6 +971,14 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
def source_for_pipeline(self, config: CustomSourceConfig, inputs: SourceInputs) -> SourceResponse:
try:
manifest = self._assemble_manifest(config)
+ # A model-backed OAuth2 source loads its live secrets + minted token from the
+ # CustomOAuth2Integration row here (sync time, DB-capable), which also writes back a rotated
+ # refresh token. _assemble_manifest already skipped the static job_inputs secrets for it.
+ if config.auth_oauth2_integration_id:
+ # Bind the integration to the syncing source so it can't inject another source's tokens.
+ _inject_oauth2_integration_secrets(
+ manifest, config.auth_oauth2_integration_id, inputs.team_id, source_id=inputs.source_id
+ )
ok, err = validate_manifest_urls(manifest, inputs.team_id)
if not ok:
raise ManifestValidationError(err or "Manifest URL validation failed")
@@ -934,6 +1012,16 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
job_id=inputs.job_id,
db_incremental_field_last_value=last_value,
)
+ except CustomOAuth2Integration.DoesNotExist as exc:
+ # The manifest points at an OAuth2 integration row that no longer resolves for this
+ # team (deleted, wrong team, or a dangling auth_oauth2_integration_id). It's a permanent
+ # config error — the row won't reappear on a retry — but it's neither a ValueError nor a
+ # 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."
+ ) from exc
except ValueError as exc:
# A malformed manifest, a missing resource, or a broken parent
# reference is a permanent, deterministic failure — retrying the sync
@@ -993,6 +1081,8 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
team_id: int,
resource_name: str,
max_rows: int = PREVIEW_DEFAULT_ROWS,
+ *,
+ owner_user_id: Optional[int] = None,
) -> "PreviewResult":
"""Fetch a bounded first page of rows for one manifest resource.
@@ -1021,6 +1111,38 @@ 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
+ # (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.
+ if config.auth_oauth2_integration_id:
+ try:
+ # Preview runs before the source exists, so the integration must not already back another
+ # source — otherwise a preview could read another source's data with its tokens.
+ _inject_oauth2_integration_secrets(
+ 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
+ except 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
+ # the injected secrets redacted out of the message.
+ auth_config = manifest.get("client", {}).get("auth", {})
+ injected_secrets = tuple(
+ str(auth_config[key])
+ for key in ("client_secret", "refresh_token", "access_token")
+ if auth_config.get(key)
+ )
+ return PreviewResult(
+ rows=[],
+ row_count=0,
+ columns=[],
+ error=_redact_secrets(strip_oauth2_permanent_marker(str(exc)), injected_secrets),
+ )
+
chain = _fanout_chain(manifest, resource_name)
client = manifest["client"]
@@ -1311,6 +1433,11 @@ def _inject_auth_secrets(manifest: dict[str, Any], config: CustomSourceConfig) -
elif auth_type == "http_basic" and config.auth_password:
auth["password"] = config.auth_password
elif auth_type == "oauth2":
+ # A model-backed source (auth_oauth2_integration_id set) gets its live secrets + minted token
+ # from the CustomOAuth2Integration row at sync time (see _inject_oauth2_integration_secrets),
+ # so skip the static job_inputs secrets entirely — they aren't the source of truth here.
+ if config.auth_oauth2_integration_id:
+ return
# The non-secret oauth fields (client_id / token_url / grant_type / knobs) are
# already in the manifest; inject only the secrets. client_credentials needs just
# the client_secret; the refresh_token grant also needs the refresh token.
@@ -1320,6 +1447,113 @@ def _inject_auth_secrets(manifest: dict[str, Any], config: CustomSourceConfig) -
auth["refresh_token"] = config.auth_oauth2_refresh_token
+def _authorize_integration_for_source(
+ integration: CustomOAuth2Integration,
+ team_id: int,
+ *,
+ source_id: Optional[str],
+ forbid_bound: bool,
+ owner_user_id: Optional[int] = None,
+) -> None:
+ """Fail closed unless ``integration`` belongs to — or is owned by the user setting up — the source
+ about to use its secrets.
+
+ Scoping the lookup by ``team_id`` alone lets any source in a team adopt another source's integration
+ UUID and exfiltrate its OAuth client secret + tokens. Binding the row to its source closes that:
+
+ * sync (``source_id`` set): the row must already belong to this source. An unbound row is claimed for
+ it on first use (trust-on-first-use), so no second source can adopt it afterwards; a row bound to a
+ different source is rejected.
+ * preview/create (``forbid_bound``): there's no source yet, so the row must be unbound — it can't
+ already be backing another source.
+
+ An unbound row is a floating credential, so a request-context caller (``owner_user_id`` set) may only
+ consume one it created — otherwise a teammate could adopt someone else's not-yet-bound integration.
+ At sync there's no acting user; the source already passed this same owner check at create/update, so
+ the first-use claim is safe.
+
+ Rejection raises ``CustomOAuth2Integration.DoesNotExist`` so each caller's existing "integration no
+ longer exists" handling turns it into the right non-retryable / 400 response.
+ """
+ foreign_unbound = owner_user_id is not None and integration.created_by_id != owner_user_id
+ bound_source_id = integration.external_data_source_id
+ if source_id is not None:
+ if bound_source_id is None:
+ if foreign_unbound:
+ raise CustomOAuth2Integration.DoesNotExist("OAuth2 integration is not available for this source.")
+ # Atomically claim the unbound row for this source. A guarded UPDATE (not a save) loses the
+ # race cleanly if another source's first sync claims it first, and an IntegrityError means the
+ # source already has a different integration bound — both fall through to the match check below,
+ # which fails closed.
+ try:
+ claimed = (
+ CustomOAuth2Integration.objects.for_team(team_id)
+ .filter(pk=integration.pk, external_data_source__isnull=True)
+ .update(external_data_source_id=source_id)
+ )
+ except IntegrityError:
+ claimed = 0
+ if claimed:
+ integration.external_data_source_id = source_id # keep the in-memory row consistent
+ return
+ bound_source_id = (
+ CustomOAuth2Integration.objects.for_team(team_id)
+ .values_list("external_data_source_id", flat=True)
+ .get(pk=integration.pk)
+ )
+ if str(bound_source_id) != str(source_id):
+ raise CustomOAuth2Integration.DoesNotExist("OAuth2 integration is not bound to this source.")
+ elif forbid_bound:
+ if bound_source_id is not None:
+ raise CustomOAuth2Integration.DoesNotExist("OAuth2 integration is already bound to another source.")
+ if foreign_unbound:
+ raise CustomOAuth2Integration.DoesNotExist("OAuth2 integration is not available for this source.")
+
+
+def _inject_oauth2_integration_secrets(
+ manifest: dict[str, Any],
+ integration_id: str,
+ team_id: int,
+ *,
+ source_id: Optional[str] = None,
+ forbid_bound: bool = False,
+ owner_user_id: Optional[int] = None,
+) -> None:
+ """Inject a model-backed OAuth2 source's minted access token into ``client.auth`` as a static bearer.
+
+ Mutates ``manifest`` in place. Runs at sync, create-time validation, and preview — all DB-capable
+ seams where ``team_id`` is known — never on the schema-listing manifest assembly. ``get_access_token()``
+ mints + persists up front (under a row lock), so this is the seam where a rotating provider's new
+ single-use refresh token gets written back before the next sync would reuse the consumed one.
+
+ Only the minted access token is seeded — never the refresh_token/client_secret — and
+ ``manages_own_token=False`` tells the REST engine to send it without ever minting. A mid-sync re-mint
+ would consume a single-use refresh token whose rotation the engine can't persist; instead an expired
+ token surfaces as a retryable 401 and the retry re-mints up front through the row.
+
+ ``source_id`` / ``forbid_bound`` bind the integration to the source using it; see
+ ``_authorize_integration_for_source``.
+ """
+ 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
+ integration = get_custom_oauth2_integration(integration_id, team_id)
+ _authorize_integration_for_source(
+ integration, team_id, source_id=source_id, forbid_bound=forbid_bound, owner_user_id=owner_user_id
+ )
+ integration.get_access_token()
+ auth["access_token"] = integration.sensitive_config.get("access_token")
+ auth["manages_own_token"] = False
+ # Strip any minting material so the engine structurally cannot re-mint mid-sync (belt-and-suspenders
+ # to manages_own_token=False): the row is the only place a single-use refresh token may be rotated +
+ # persisted.
+ auth.pop("client_secret", None)
+ auth.pop("refresh_token", None)
+
+
def _incremental_field_type(raw: Any) -> IncrementalFieldType:
"""Map a manifest-declared cursor type to an :class:`IncrementalFieldType`.
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.py
index db7b40d6cb2f..8815ee556c23 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
@@ -6,6 +6,7 @@ from typing import Any, cast
from urllib.parse import quote
from freezegun import freeze_time
+from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase, override_settings
@@ -15,6 +16,10 @@ from parameterized import parameterized
from requests import Response
from urllib3.response import HTTPResponse
+from posthog.models import User
+
+from products.warehouse_sources.backend.models import ExternalDataSource
+from products.warehouse_sources.backend.models.custom_oauth2_integration import CustomOAuth2Integration
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (
OAUTH2_PERMANENT_ERROR_MARKER,
APIKeyAuth,
@@ -23,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
OAuth2Auth,
OAuth2AuthRequestError,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import create_auth
from products.warehouse_sources.backend.temporal.data_imports.sources.custom.source import (
MAX_MANIFEST_RESOURCES,
PREVIEW_MAX_FANOUT_PARENTS,
@@ -35,6 +41,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.custom.sou
ManifestValidationError,
PreviewResponseTooLargeError,
_fanout_chain,
+ _inject_oauth2_integration_secrets,
_json_type_label,
_PreviewSession,
_read_capped_text,
@@ -49,6 +56,15 @@ from products.warehouse_sources.backend.temporal.data_imports.util import NonRet
from products.warehouse_sources.backend.types import IncrementalFieldType
AUTH_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth"
+SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.make_tracked_session"
+
+
+def _token_response(status_code: int = 200, payload: dict[str, Any] | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ # The token exchange reads a capped `response.raw.read(...)` then json.loads — seed the raw body.
+ response.raw.read.return_value = json.dumps(payload if payload is not None else {}).encode()
+ return response
def validate_manifest(manifest: Any) -> None:
@@ -462,6 +478,305 @@ class TestCustomSourceAssembleManifest(SimpleTestCase):
assert "client_secret" not in auth
assert "refresh_token" not in auth
+ def test_oauth2_skips_static_secrets_when_integration_backed(self):
+ # When the source points at a CustomOAuth2Integration, the static job_inputs secrets must NOT be
+ # injected here — the row is the source of truth and supplies them at sync time. Leaking the
+ # static ones would let a stale/duplicate secret override the model's live credentials.
+ manifest = _minimal_manifest()
+ manifest["client"]["auth"] = {
+ "type": "oauth2",
+ "client_id": "cid",
+ "token_url": "https://auth.example.com/token",
+ }
+ source = CustomSource()
+ config = CustomSourceConfig(
+ manifest_json=json.dumps(manifest),
+ auth_oauth2_client_secret="cs_secret",
+ auth_oauth2_refresh_token="rt_secret",
+ auth_oauth2_integration_id="11111111-1111-1111-1111-111111111111",
+ )
+ auth = source._assemble_manifest(config)["client"]["auth"]
+ assert "client_secret" not in auth
+ assert "refresh_token" not in auth
+
+
+class TestCustomSourceOAuth2IntegrationWiring(BaseTest):
+ def _make_integration(
+ self, *, external_data_source: ExternalDataSource | None = None, created_by=None, **secret_overrides
+ ) -> CustomOAuth2Integration:
+ return CustomOAuth2Integration.objects.for_team(self.team.pk).create(
+ team=self.team,
+ external_data_source=external_data_source,
+ created_by=created_by,
+ config={"token_url": "https://auth.example.com/token", "client_id": "cid", "grant_type": "refresh_token"},
+ sensitive_config={"client_secret": "cs", "refresh_token": "orig-RT", **secret_overrides},
+ )
+
+ 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 _oauth2_manifest(self) -> dict:
+ manifest = _minimal_manifest()
+ manifest["client"]["auth"] = {
+ "type": "oauth2",
+ "client_id": "cid",
+ "token_url": "https://auth.example.com/token",
+ "grant_type": "refresh_token",
+ }
+ return manifest
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_injects_static_bearer_and_writes_back_rotation(self, mock_session):
+ # The Calendly path end-to-end at the wiring seam: minting up front persists the rotated
+ # single-use refresh token, and the manifest is seeded with a static bearer (the minted access
+ # token, manages_own_token=False) — never the refresh_token/client_secret — so the engine
+ # structurally can't re-mint and burn an unpersisted rotation.
+ mock_session.return_value.post.return_value = _token_response(
+ payload={"access_token": "minted-AT", "expires_in": 3600, "refresh_token": "rotated-RT"}
+ )
+ integration = self._make_integration()
+ manifest = self._oauth2_manifest()
+
+ _inject_oauth2_integration_secrets(manifest, str(integration.pk), self.team.pk)
+
+ auth = manifest["client"]["auth"]
+ assert auth["access_token"] == "minted-AT"
+ assert auth["manages_own_token"] is False
+ # No minting material reaches the engine.
+ assert "refresh_token" not in auth
+ assert "client_secret" not in auth
+ # The rotation was persisted, so the next sync reads the rotated token from the row.
+ fresh = CustomOAuth2Integration.objects.for_team(self.team.pk).get(pk=integration.pk)
+ assert fresh.sensitive_config["refresh_token"] == "rotated-RT"
+
+ @freeze_time("2025-01-01T00:00:00Z")
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_reuses_cached_token_without_minting(self, mock_session):
+ # A still-valid cached token means no mint at all — the manifest is seeded straight from the row.
+ future = (datetime.now(UTC) + timedelta(hours=1)).isoformat()
+ integration = self._make_integration(access_token="cached-AT", token_expiry=future)
+ manifest = self._oauth2_manifest()
+
+ _inject_oauth2_integration_secrets(manifest, str(integration.pk), self.team.pk)
+
+ mock_session.return_value.post.assert_not_called()
+ auth = manifest["client"]["auth"]
+ assert auth["access_token"] == "cached-AT"
+ assert auth["manages_own_token"] is False
+ # No refresh material is seeded — the engine treats it as a static bearer and never mints.
+ assert "refresh_token" not in auth
+
+ @freeze_time("2025-01-01T00:00:00Z")
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_post_injection_manifest_builds_static_bearer_that_never_mints(self, mock_session):
+ # End-to-end seam: feed the injected client.auth through the engine's own auth construction
+ # (`create_auth` -> `auth_class(**exclude_keys(...))`) and drive a request. manages_own_token=False
+ # must survive the unpacking and short-circuit minting — the token carries no expiry, so without
+ # the flag the engine would treat it as expired and mint (burning an unpersisted rotation).
+ # A key/kwarg rename would also crash construction here. No token-endpoint POST may happen.
+ future = (datetime.now(UTC) + timedelta(hours=1)).isoformat()
+ integration = self._make_integration(access_token="cached-AT", token_expiry=future)
+ manifest = self._oauth2_manifest()
+
+ _inject_oauth2_integration_secrets(manifest, str(integration.pk), self.team.pk)
+
+ auth = create_auth(manifest["client"]["auth"])
+ assert isinstance(auth, OAuth2Auth)
+ assert auth.manages_own_token is False
+ request = MagicMock()
+ request.headers = {}
+ auth(request)
+ assert request.headers["Authorization"] == "Bearer cached-AT"
+ mock_session.return_value.post.assert_not_called()
+
+ @patch(SOURCE_MODULE)
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_validate_credentials_mints_through_integration(self, mock_token_session, mock_probe_session):
+ # The bug: an integration-backed OAuth2 source has no refresh token in job_inputs, so
+ # validate_credentials used to build a refresh_token-grant OAuth2Auth with no token and fail the
+ # pre-mint with "A refresh_token is required". The fix seeds the manifest from the row first, so
+ # validation mints through the integration and the data probe reuses the seeded token.
+ mock_token_session.return_value.post.return_value = _token_response(
+ payload={"access_token": "minted-AT", "expires_in": 3600}
+ )
+ mock_probe_session.return_value.request.return_value = MagicMock(status_code=200, text="{}")
+ integration = self._make_integration()
+ config = CustomSourceConfig(
+ manifest_json=json.dumps(self._oauth2_manifest()),
+ auth_oauth2_integration_id=str(integration.pk),
+ )
+
+ ok, err = CustomSource().validate_credentials(config, team_id=self.team.pk)
+
+ assert ok, err
+ assert "refresh_token is required" not in (err or "")
+
+ @patch(SOURCE_MODULE)
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_validate_credentials_does_not_re_mint_for_integration_backed(self, mock_token_session, mock_probe_session):
+ # The rotation-without-writeback guard: for an integration-backed source the token is minted once
+ # through the row (which persists the rotated single-use refresh token). The data probe must reuse
+ # that seeded token and NOT mint a second time — a second mint would rotate the refresh token
+ # without writing it back, orphaning the row on a consumed token. Assert exactly one token POST,
+ # and that the stored refresh token is the one the integration path rotated to (not double-rotated).
+ mock_token_session.return_value.post.return_value = _token_response(
+ payload={"access_token": "minted-AT", "expires_in": 3600, "refresh_token": "rotated-RT"}
+ )
+ mock_probe_session.return_value.request.return_value = MagicMock(status_code=200, text="{}")
+ integration = self._make_integration()
+ config = CustomSourceConfig(
+ manifest_json=json.dumps(self._oauth2_manifest()),
+ auth_oauth2_integration_id=str(integration.pk),
+ )
+
+ ok, err = CustomSource().validate_credentials(config, team_id=self.team.pk)
+
+ assert ok, err
+ assert mock_token_session.return_value.post.call_count == 1
+ fresh = CustomOAuth2Integration.objects.for_team(self.team.pk).get(pk=integration.pk)
+ assert fresh.sensitive_config["refresh_token"] == "rotated-RT"
+
+ def test_validate_credentials_missing_integration_returns_clear_error(self):
+ # A dangling / foreign auth_oauth2_integration_id must surface a clear message, not crash.
+ config = CustomSourceConfig(
+ manifest_json=json.dumps(self._oauth2_manifest()),
+ auth_oauth2_integration_id="11111111-1111-1111-1111-111111111111",
+ )
+
+ ok, err = CustomSource().validate_credentials(config, team_id=self.team.pk)
+
+ assert not ok
+ assert "no longer exists" in (err or "")
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_validate_credentials_on_update_rejects_another_sources_integration(self, mock_session):
+ # Updating source A must not validate with source B's integration UUID — the probe would otherwise
+ # mint and send B's token to the (attacker-supplied) manifest host. Rejected before any mint.
+ owner = self._make_source("owner")
+ attacker = self._make_source("attacker")
+ integration = self._make_integration(external_data_source=owner)
+ config = CustomSourceConfig(
+ manifest_json=json.dumps(self._oauth2_manifest()),
+ auth_oauth2_integration_id=str(integration.pk),
+ )
+
+ 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 "")
+ mock_session.return_value.post.assert_not_called()
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_validate_credentials_on_create_rejects_bound_integration(self, mock_session):
+ # Create/setup validation has no source yet, so an already-bound integration (another source's) is
+ # rejected before its token is minted.
+ owner = self._make_source("owner")
+ integration = self._make_integration(external_data_source=owner)
+ config = CustomSourceConfig(
+ manifest_json=json.dumps(self._oauth2_manifest()),
+ auth_oauth2_integration_id=str(integration.pk),
+ )
+
+ ok, err = CustomSource().validate_credentials(config, team_id=self.team.pk)
+
+ assert not ok
+ assert "no longer exists" in (err or "")
+ mock_session.return_value.post.assert_not_called()
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_sync_rejects_integration_bound_to_another_source(self, mock_session):
+ # The cross-source theft guard: at sync time a source cannot use an integration that belongs to a
+ # different source, even within the same team — no token is minted and the lookup fails closed.
+ owner = self._make_source("owner")
+ attacker = self._make_source("attacker")
+ integration = self._make_integration(external_data_source=owner)
+
+ with self.assertRaises(CustomOAuth2Integration.DoesNotExist):
+ _inject_oauth2_integration_secrets(
+ self._oauth2_manifest(), str(integration.pk), self.team.pk, source_id=str(attacker.pk)
+ )
+ mock_session.return_value.post.assert_not_called()
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_sync_binds_unbound_integration_to_source_on_first_use(self, mock_session):
+ # Trust-on-first-use: the first sync claims an unbound integration for its source, so no second
+ # source can adopt it afterwards (the reject test above then applies).
+ mock_session.return_value.post.return_value = _token_response(
+ payload={"access_token": "minted-AT", "expires_in": 3600}
+ )
+ source = self._make_source()
+ integration = self._make_integration() # unbound
+ manifest = self._oauth2_manifest()
+
+ _inject_oauth2_integration_secrets(manifest, str(integration.pk), self.team.pk, source_id=str(source.pk))
+
+ fresh = CustomOAuth2Integration.objects.for_team(self.team.pk).get(pk=integration.pk)
+ assert str(fresh.external_data_source_id) == str(source.pk)
+ assert manifest["client"]["auth"]["access_token"] == "minted-AT"
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_sync_allows_integration_bound_to_its_own_source(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response(
+ payload={"access_token": "minted-AT", "expires_in": 3600}
+ )
+ source = self._make_source()
+ integration = self._make_integration(external_data_source=source)
+ manifest = self._oauth2_manifest()
+
+ _inject_oauth2_integration_secrets(manifest, str(integration.pk), self.team.pk, source_id=str(source.pk))
+
+ assert manifest["client"]["auth"]["access_token"] == "minted-AT"
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_preview_forbids_integration_bound_to_a_source(self, mock_session):
+ # Preview runs before a source exists, so an already-bound integration (another source's) must be
+ # rejected — otherwise a preview could read that source's data with its tokens.
+ owner = self._make_source("owner")
+ integration = self._make_integration(external_data_source=owner)
+
+ with self.assertRaises(CustomOAuth2Integration.DoesNotExist):
+ _inject_oauth2_integration_secrets(
+ self._oauth2_manifest(), str(integration.pk), self.team.pk, forbid_bound=True
+ )
+ mock_session.return_value.post.assert_not_called()
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_inject_rejects_unbound_integration_owned_by_another_user(self, mock_session):
+ # An unbound integration is a floating credential: in a request context (owner_user_id set) only its
+ # creator may consume it, so a teammate can't adopt someone else's not-yet-bound integration UUID.
+ integration = self._make_integration(created_by=self.user) # unbound, created by self.user
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "pw12345678")
+
+ with self.assertRaises(CustomOAuth2Integration.DoesNotExist):
+ _inject_oauth2_integration_secrets(
+ self._oauth2_manifest(),
+ str(integration.pk),
+ self.team.pk,
+ forbid_bound=True,
+ owner_user_id=other_user.pk,
+ )
+ mock_session.return_value.post.assert_not_called()
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_inject_allows_unbound_integration_owned_by_requester(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response(
+ payload={"access_token": "minted-AT", "expires_in": 3600}
+ )
+ integration = self._make_integration(created_by=self.user)
+ manifest = self._oauth2_manifest()
+
+ _inject_oauth2_integration_secrets(
+ manifest, str(integration.pk), self.team.pk, forbid_bound=True, owner_user_id=self.user.pk
+ )
+
+ assert manifest["client"]["auth"]["access_token"] == "minted-AT"
+
class TestCustomSourceGetSchemas(SimpleTestCase):
def test_returns_one_schema_per_resource(self):
@@ -1047,6 +1362,29 @@ class TestCustomSourceSourceForPipeline(SimpleTestCase):
with self.assertRaises(NonRetryableException):
source.source_for_pipeline(config, inputs)
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.get_custom_oauth2_integration"
+ )
+ def test_missing_oauth2_integration_raises_non_retryable(self, mock_get_integration):
+ # A dangling auth_oauth2_integration_id (deleted row / wrong team) raises DoesNotExist at the
+ # sync seam. It's neither a ValueError nor a message the substring classifier matches, so without
+ # explicit handling it would retry until the activity budget is exhausted — assert it fails fast.
+ mock_get_integration.side_effect = CustomOAuth2Integration.DoesNotExist
+ manifest = _minimal_manifest()
+ manifest["client"]["auth"] = {
+ "type": "oauth2",
+ "client_id": "cid",
+ "token_url": "https://auth.example.com/token",
+ }
+ source = CustomSource()
+ config = CustomSourceConfig(
+ manifest_json=json.dumps(manifest),
+ auth_oauth2_integration_id="11111111-1111-1111-1111-111111111111",
+ )
+ inputs = MagicMock(team_id=999, schema_name="users")
+ with self.assertRaises(NonRetryableException):
+ source.source_for_pipeline(config, inputs)
+
@parameterized.expand(
[("default_asc", None, "asc"), ("explicit_asc", "asc", "asc"), ("explicit_desc", "desc", "desc")]
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 553234f4b9ac..818a7340bccc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -878,6 +878,7 @@ class CustomSourceConfig(config.Config):
auth_password: str | None = None
auth_oauth2_client_secret: str | None = None
auth_oauth2_refresh_token: str | None = None
+ auth_oauth2_integration_id: str | None = None
@config.config
diff --git a/products/warehouse_sources/backend/tests/test_custom_oauth2_integration.py b/products/warehouse_sources/backend/tests/test_custom_oauth2_integration.py
index cafea2e662d7..810c7aa4f13a 100644
--- a/products/warehouse_sources/backend/tests/test_custom_oauth2_integration.py
+++ b/products/warehouse_sources/backend/tests/test_custom_oauth2_integration.py
@@ -8,6 +8,8 @@ from unittest.mock import MagicMock, patch
from django.contrib.admin.sites import AdminSite
from django.db import IntegrityError
+from parameterized import parameterized
+
from posthog.models import Team
from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED
from posthog.models.scoping.manager import TeamScopeError
@@ -150,11 +152,41 @@ class TestCustomOAuth2Integration(BaseTest):
assert custom_oauth2_refresh_counter.labels("success")._value.get() == success_before + 1
assert custom_oauth2_refresh_counter.labels("failed")._value.get() == failed_before + 1
+ @parameterized.expand([("before_midpoint", 20, False), ("after_midpoint", 40, True)])
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_get_access_token_refreshes_at_lifetime_midpoint(
+ self, _name: str, minutes_elapsed: int, expect_refresh: bool, mock_session: MagicMock
+ ):
+ # Proactive half-life refresh, mirroring OauthIntegration.access_token_expired: a 60-minute token
+ # is reused before its 30-minute midpoint and re-minted after it. A flat pre-expiry buffer would
+ # instead reuse it until the last minute — handing a long sync a near-dead token, since the engine
+ # no longer refreshes mid-sync and this up-front runway is all there is.
+ mock_session.return_value.post.return_value = _token_response(
+ payload={"access_token": "minted-fresh", "expires_in": 3600}
+ )
+ now = datetime.now(UTC)
+ integration = self._make_integration(
+ config={"refreshed_at": int((now - timedelta(minutes=minutes_elapsed)).timestamp())},
+ sensitive_config={
+ "access_token": "cached-token",
+ "token_expiry": (now + timedelta(minutes=60 - minutes_elapsed)).isoformat(),
+ },
+ )
+
+ token = integration.get_access_token()
+
+ if expect_refresh:
+ assert token == "minted-fresh"
+ mock_session.return_value.post.assert_called_once()
+ else:
+ assert token == "cached-token"
+ mock_session.return_value.post.assert_not_called()
+
@patch(f"{AUTH_MODULE}.make_tracked_session")
def test_short_lived_token_not_treated_as_expired_right_after_mint(self, mock_session):
- # Capped buffer: a token whose whole TTL (30s) is under the flat 60s buffer would, with a flat
- # buffer, read as already-expired the instant it's minted and re-mint on every call. With the
- # buffer capped at lifetime/2 (15s), a freshly-minted token stays valid and is reused.
+ # Half-life refresh: a freshly-minted token sits at the very start of its lifetime, well before the
+ # midpoint, so it's reused rather than re-minted — even for a very short (30s) TTL, where a flat
+ # pre-expiry buffer would have read it as already-expired the instant it's minted.
now = datetime.now(UTC)
integration = self._make_integration(
config={"refreshed_at": int(now.timestamp())},