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): add CustomOAuth2Integration token store (#66769)

Marcus Hof90b61a6ad779
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index ee2f30b4985a..c207dd35e4b2 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -90,6 +90,7 @@ rules:
|CoreMemory
|CustomerJourney
|CustomerProfileConfig
+ |CustomOAuth2Integration
|CustomPropertyDefinition
|CustomPropertyValue
|DAG
@@ -359,6 +360,7 @@ rules:
|CoreMemory
|CustomerJourney
|CustomerProfileConfig
+ |CustomOAuth2Integration
|CustomPropertyDefinition
|CustomPropertyValue
|DAG
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 763b45626e71..fba5c5c0554d 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -635,6 +635,9 @@ field_exclusions: dict[AuditableScope, list[str]] = {
"connection_id",
"destination_id",
"are_tables_created",
+ # Reverse relation to a fail-closed model: reading through it in `changes_between` raises
+ # TeamScopeError when a source is saved outside request scope, and it isn't source-config intent.
+ "custom_oauth2_integrations",
],
"ExternalDataSchema": [
"status",
diff --git a/products/warehouse_sources/backend/admin/__init__.py b/products/warehouse_sources/backend/admin/__init__.py
index 9950db8399c0..3a5c6ee02ad6 100644
--- a/products/warehouse_sources/backend/admin/__init__.py
+++ b/products/warehouse_sources/backend/admin/__init__.py
@@ -1,6 +1,7 @@
# Importing these submodules fires their `@admin.register` decorators when
# `autodiscover_modules("admin")` imports this package.
from products.warehouse_sources.backend.admin import ( # noqa: F401
+ custom_oauth2_integration_admin,
data_warehouse_table_admin,
external_data_schema_admin,
)
diff --git a/products/warehouse_sources/backend/admin/custom_oauth2_integration_admin.py b/products/warehouse_sources/backend/admin/custom_oauth2_integration_admin.py
new file mode 100644
index 000000000000..058632ff1337
--- /dev/null
+++ b/products/warehouse_sources/backend/admin/custom_oauth2_integration_admin.py
@@ -0,0 +1,63 @@
+from django.contrib import admin
+from django.db.models import QuerySet
+from django.http import HttpRequest
+from django.utils.html import format_html
+
+from products.warehouse_sources.backend.models.custom_oauth2_integration import CustomOAuth2Integration
+
+
[email protected](CustomOAuth2Integration)
+class CustomOAuth2IntegrationAdmin(admin.ModelAdmin):
+ list_select_related = ("team", "created_by", "external_data_source")
+ list_display = ("id", "team_link", "external_data_source", "has_errors", "created_by", "created_at")
+ list_display_links = ("id",)
+ list_filter = (("created_at", admin.DateFieldListFilter),)
+ search_fields = ("id", "team__name", "team__organization__name", "external_data_source__id")
+ ordering = ("-created_at",)
+ # All FKs are read-only here, which also keeps Django from rendering a <select> that would load the
+ # whole target table per row (CLAUDE.md FK-widget rule).
+ readonly_fields = ("id", "team", "external_data_source", "created_by", "created_at", "updated_at")
+
+ # `sensitive_config` (client_secret + tokens) is deliberately omitted from every fieldset — redaction
+ # by omission, like IntegrationAdmin. It must never be rendered, even read-only.
+ fieldsets = [
+ (
+ None,
+ {
+ "fields": ["id", "team", "external_data_source", "created_by", "created_at", "updated_at"],
+ },
+ ),
+ (
+ "Config",
+ {
+ "fields": ["config", "errors"],
+ },
+ ),
+ ]
+
+ def get_queryset(self, request: HttpRequest) -> QuerySet[CustomOAuth2Integration]:
+ # `objects` is the fail-closed TeamScopedManager, which raises TeamScopeError without an ambient
+ # team scope — and admin runs outside request/team scope, so the default manager would 500 every
+ # changelist/detail render. Read cross-team through `unscoped()`, the prescribed escape hatch for
+ # framework internals (this admin is staff-only and inspection-only).
+ return CustomOAuth2Integration.objects.unscoped()
+
+ # Inspection-only. The row holds OAuth2 secrets and is written solely by the sync worker
+ # (refresh_and_persist) under a row lock + team scope; editing it from admin would bypass that scope.
+ # Reconnect/edit flows live in the product UI.
+ def has_add_permission(self, request) -> bool:
+ return False
+
+ def has_change_permission(self, request, obj=None) -> bool:
+ return False
+
+ def has_delete_permission(self, request, obj=None) -> bool:
+ return False
+
+ @admin.display(description="Team")
+ def team_link(self, obj: CustomOAuth2Integration) -> str:
+ return format_html("{} ({})", obj.team.name, obj.team_id)
+
+ @admin.display(description="Errors", boolean=True)
+ def has_errors(self, obj: CustomOAuth2Integration) -> bool:
+ return bool(obj.errors)
diff --git a/products/warehouse_sources/backend/facade/models.py b/products/warehouse_sources/backend/facade/models.py
index ba0ba1ed24aa..3523df901b1a 100644
--- a/products/warehouse_sources/backend/facade/models.py
+++ b/products/warehouse_sources/backend/facade/models.py
@@ -18,6 +18,10 @@ from products.warehouse_sources.backend.models.credential import (
DataWarehouseCredential,
get_or_create_datawarehouse_credential,
)
+from products.warehouse_sources.backend.models.custom_oauth2_integration import (
+ CustomOAuth2Integration,
+ get_custom_oauth2_integration,
+)
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob, get_latest_run_if_exists
from products.warehouse_sources.backend.models.external_data_schema import (
ExternalDataSchema,
@@ -50,6 +54,7 @@ from products.warehouse_sources.backend.models.util import (
)
__all__ = [
+ "CustomOAuth2Integration",
"DataWarehouseCredential",
"DataWarehouseTable",
"DataWarehouseTableColumns",
@@ -62,6 +67,7 @@ __all__ = [
"WarehouseColumnStatistics",
"acreate_datawarehousetable",
"asave_datawarehousetable",
+ "get_custom_oauth2_integration",
"get_all_schemas_for_source_id",
"get_direct_external_data_source_for_connection",
"get_latest_run_if_exists",
diff --git a/products/warehouse_sources/backend/migrations/0054_custom_oauth2_integration.py b/products/warehouse_sources/backend/migrations/0054_custom_oauth2_integration.py
new file mode 100644
index 000000000000..f3468e46d698
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0054_custom_oauth2_integration.py
@@ -0,0 +1,79 @@
+# Generated by Django 5.2.14 on 2026-06-29 14:46
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+from django.db.models import Q
+
+import posthog.models.utils
+import posthog.helpers.encrypted_fields
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1245_duckgres_sink_schema_state"),
+ ("warehouse_sources", "0053_alter_externaldatasource_source_type_and_more"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="CustomOAuth2Integration",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("config", models.JSONField(default=dict)),
+ (
+ "sensitive_config",
+ posthog.helpers.encrypted_fields.EncryptedJSONField(default=dict),
+ ),
+ ("errors", models.TextField(blank=True, default="")),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "external_data_source",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="custom_oauth2_integrations",
+ to="warehouse_sources.externaldatasource",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(
+ condition=Q(external_data_source__isnull=False),
+ fields=("team", "external_data_source"),
+ name="unique_custom_oauth2_integration_per_source",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txt
index f39f75e8a05a..d344bc5dcb1b 100644
--- a/products/warehouse_sources/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0053_alter_externaldatasource_source_type_and_more
+0054_custom_oauth2_integration
diff --git a/products/warehouse_sources/backend/models/__init__.py b/products/warehouse_sources/backend/models/__init__.py
index 1e223c01ba47..ebc3ca27a61a 100644
--- a/products/warehouse_sources/backend/models/__init__.py
+++ b/products/warehouse_sources/backend/models/__init__.py
@@ -1,6 +1,7 @@
from .column_annotation import WarehouseColumnAnnotation
from .column_statistics import WarehouseColumnStatistics
from .credential import DataWarehouseCredential
+from .custom_oauth2_integration import CustomOAuth2Integration
from .external_data_job import ExternalDataJob
from .external_data_schema import ExternalDataSchema
from .external_data_source import ExternalDataSource
@@ -8,6 +9,7 @@ from .pending_source_credential import PendingSourceCredential
from .table import DataWarehouseTable
__all__ = [
+ "CustomOAuth2Integration",
"DataWarehouseCredential",
"DataWarehouseTable",
"ExternalDataJob",
diff --git a/products/warehouse_sources/backend/models/custom_oauth2_integration.py b/products/warehouse_sources/backend/models/custom_oauth2_integration.py
new file mode 100644
index 000000000000..18325124ccc9
--- /dev/null
+++ b/products/warehouse_sources/backend/models/custom_oauth2_integration.py
@@ -0,0 +1,217 @@
+import time
+from datetime import UTC, datetime, timedelta
+from typing import TYPE_CHECKING, Optional
+
+from django.db import models, transaction
+from django.db.models import Q
+
+import structlog
+from prometheus_client import Counter
+
+from posthog.helpers.encrypted_fields import EncryptedJSONField
+from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED
+from posthog.models.scoping import team_scope
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDTModel, sane_repr
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import OAuth2Auth
+
+logger = structlog.get_logger(__name__)
+
+# The config-driven twin of `oauth_refresh_counter` in posthog.models.integration: a separate metric
+# since the custom store refreshes off a row-stored client rather than a kind-keyed settings client.
+custom_oauth2_refresh_counter = Counter(
+ "warehouse_custom_oauth2_refresh",
+ "Number of times a custom OAuth2 integration token refresh has been attempted",
+ labelnames=["result"],
+)
+
+# Re-mint the access token slightly before its declared expiry so a token that's still
+# valid at the check isn't rejected mid-flight. Same value as OAuth2Auth._TOKEN_EXPIRY_BUFFER —
+# redeclared here rather than imported so the model module doesn't pull the HTTP transport
+# stack onto the django.setup() model-load path.
+_TOKEN_EXPIRY_BUFFER = timedelta(seconds=60)
+
+
+class CustomOAuth2Integration(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, UUIDTModel):
+ """Encrypted token store for a Custom REST source's customer-owned OAuth2 client.
+
+ The customer brings their own OAuth2 client (`client_id` / `client_secret` / `token_url`); this row
+ is the durable home for the credentials plus the last-minted access token. Unlike the in-memory
+ [[OAuth2Auth]] used at request time, the row lets a sync **persist a rotated refresh token** so the
+ next sync doesn't fail with `invalid_grant` — required for providers that rotate single-use refresh
+ tokens with no grace window (Calendly), where an in-memory-only flow succeeds once and then fails.
+
+ Deliberately product-owned rather than an extension of the core `Integration` model: that model reads
+ client credentials from Django settings keyed by a closed `kind` enum and refreshes via a per-kind
+ dispatch chain, neither of which can represent a customer-supplied client. Here the credentials live
+ on the row and refresh is a single config-driven path through `OAuth2Auth._obtain_token()`.
+
+ `TeamScopedRootMixin` is first in the bases so its fail-closed manager wins the MRO; access outside
+ request context (Temporal activities) must go through `objects.for_team(team_id)` or a `team_scope()`
+ block — see the locked read in `refresh_and_persist`.
+ """
+
+ # db_constraint=False on the FKs to hot tables (posthog_team, posthog_user): creating a real FK
+ # constraint takes a SHARE ROW EXCLUSIVE lock on the parent, which stalls under write traffic. Team
+ # scoping is enforced at the app level by TeamScopedRootMixin. The external_data_source FK targets a
+ # non-hot table, so it keeps its constraint (and its cascade cleans the row up when the source is deleted).
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False
+ )
+ external_data_source = models.ForeignKey(
+ "warehouse_sources.ExternalDataSource",
+ on_delete=models.CASCADE,
+ null=True,
+ blank=True,
+ related_name="custom_oauth2_integrations",
+ )
+
+ # Non-secret OAuth2 config: the exact non-secret OAuth2Auth.__init__ args (client_id, token_url,
+ # grant_type, scopes, and the provider-long-tail knobs) plus `refreshed_at` (unix seconds of the
+ # last successful mint). Safe to surface to the frontend; never holds a secret.
+ config = models.JSONField(default=dict)
+ # Secret material, Fernet-encrypted at rest: client_secret, refresh_token (the rotating one),
+ # access_token (last-minted token, reused across syncs until expiry like core Integration), and
+ # token_expiry (ISO-8601). A DRF serializer over this model MUST omit this field entirely.
+ sensitive_config = EncryptedJSONField(default=dict)
+ # ERROR_TOKEN_REFRESH_FAILED while a refresh is failing (queryable broken-token state); "" on success.
+ errors = models.TextField(blank=True, default="")
+
+ __repr__ = sane_repr("id", "team_id", "external_data_source_id")
+
+ class Meta:
+ constraints = [
+ # Partial index: only enforce one integration per (team, source) for real source links.
+ # A plain UniqueConstraint is a no-op across NULL source FKs (Postgres treats NULLs as
+ # distinct), so unlinked rows would slip past it — the condition makes the name hold.
+ models.UniqueConstraint(
+ fields=["team", "external_data_source"],
+ condition=Q(external_data_source__isnull=False),
+ name="unique_custom_oauth2_integration_per_source",
+ ),
+ ]
+
+ def build_auth(self) -> "OAuth2Auth":
+ """Construct the request-time auth engine from this row's stored config + secrets."""
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import ( # noqa: PLC0415 — keep the HTTP transport stack off the django.setup() model-load path
+ OAuth2Auth,
+ )
+
+ return OAuth2Auth(
+ token_url=self.config.get("token_url"),
+ client_id=self.config.get("client_id"),
+ client_secret=self.sensitive_config.get("client_secret"),
+ grant_type=self.config.get("grant_type", "client_credentials"),
+ scopes=self.config.get("scopes"),
+ refresh_token=self.sensitive_config.get("refresh_token"),
+ access_token_name=self.config.get("access_token_name", "access_token"),
+ expires_in_name=self.config.get("expires_in_name", "expires_in"),
+ expiry_date_format=self.config.get("expiry_date_format"),
+ extra_token_request_params=self.config.get("extra_token_request_params"),
+ token_request_headers=self.config.get("token_request_headers"),
+ client_auth_method=self.config.get("client_auth_method", "body"),
+ )
+
+ @property
+ def access_token(self) -> Optional[str]:
+ """Last-minted access token, mirroring `Integration.access_token`."""
+ return self.sensitive_config.get("access_token")
+
+ def _access_token_expired(self) -> bool:
+ expiry = self.sensitive_config.get("token_expiry")
+ 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.
+ 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
+
+ def get_access_token(self) -> str:
+ """Reuse the stored token while it's valid; refresh + persist only when expired.
+
+ Reusing the cached token until expiry mints only when actually needed, which reduces
+ refresh-token rotation churn for high-frequency syncs and caches `client_credentials`
+ tokens too.
+ """
+ token = self.access_token
+ if token and not self._access_token_expired():
+ return token
+ return self.refresh_and_persist()
+
+ def refresh_and_persist(self) -> str:
+ """Mint a fresh access token and persist it (plus any rotated refresh token) under a row lock.
+
+ The config-driven twin of `OauthIntegration.refresh_access_token()`: it reads the credentials off
+ this row rather than Django settings, mints via the shipped `OAuth2Auth._obtain_token()`, and saves
+ the minted access token, its expiry, and a rotated single-use refresh token (when the provider
+ returned one) under `select_for_update()` so concurrent syncs can't lose an update. Returns the
+ fresh access token. On a token-endpoint failure the row is marked with `ERROR_TOKEN_REFRESH_FAILED`
+ and the original error is re-raised.
+ """
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import ( # noqa: PLC0415 — see build_auth
+ OAuth2AuthRequestError,
+ )
+
+ # team_scope(): this runs in a Temporal activity, outside the request context the fail-closed
+ # manager needs, so the locked read below would raise TeamScopeError without an ambient scope.
+ with team_scope(self.team_id):
+ try:
+ # Mint under the row lock so concurrent syncs serialize: each waits, then re-reads the
+ # rotated refresh token before minting its own — a lost update here would orphan a
+ # rotating provider on a stale single-use token.
+ with transaction.atomic():
+ row = CustomOAuth2Integration.objects.select_for_update().get(pk=self.pk)
+ auth = row.build_auth()
+ auth._obtain_token()
+ row.sensitive_config["access_token"] = auth.token
+ row.sensitive_config["token_expiry"] = auth.token_expiry.isoformat() if auth.token_expiry else None
+ # Rotating providers (e.g. Calendly) return a new single-use refresh token on every
+ # mint; persist it so the next sync doesn't reuse the now-rejected one. Non-rotating
+ # providers leave rotated_refresh_token None, so the stored refresh token is untouched.
+ if auth.rotated_refresh_token:
+ row.sensitive_config["refresh_token"] = auth.rotated_refresh_token
+ row.config["refreshed_at"] = int(time.time())
+ row.errors = ""
+ row.save(update_fields=["sensitive_config", "config", "errors"])
+ except OAuth2AuthRequestError:
+ # The atomic block above rolled back, so the broken-token state needs its own committed
+ # write to survive (and be queryable). A direct queryset UPDATE — not a model save —
+ # touches only `errors`, leaving the stored refresh token intact for re-entry to replace.
+ CustomOAuth2Integration.objects.filter(pk=self.pk).update(errors=ERROR_TOKEN_REFRESH_FAILED)
+ self.errors = ERROR_TOKEN_REFRESH_FAILED
+ custom_oauth2_refresh_counter.labels("failed").inc()
+ logger.warning("Failed to refresh custom OAuth2 token", integration_id=str(self.pk))
+ raise
+
+ custom_oauth2_refresh_counter.labels("success").inc()
+
+ # Keep the in-memory instance the caller holds consistent with what we just persisted.
+ self.sensitive_config = row.sensitive_config
+ self.config = row.config
+ self.errors = row.errors
+
+ # `_obtain_token()` sets the token or raises above; guard so the `str` return type holds.
+ if auth.token is None:
+ raise OAuth2AuthRequestError("Token endpoint returned no access token")
+ return auth.token
+
+
+def get_custom_oauth2_integration(integration_id: str, team_id: int) -> CustomOAuth2Integration:
+ """Load a custom OAuth2 integration for a team, outside request context (Temporal activities).
+
+ Uses `for_team()` — the prescribed fail-closed escape hatch — so a caller can never read another
+ team's credentials by id. Raises `CustomOAuth2Integration.DoesNotExist` when the id isn't this team's.
+ """
+ return CustomOAuth2Integration.objects.for_team(team_id).get(id=integration_id)
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 3802856882b7..f44f56c62935 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
@@ -178,6 +178,10 @@ 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
+ # 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.
self.token_expiry: Optional[datetime] = None
@@ -292,6 +296,12 @@ class OAuth2Auth(BearerTokenAuth):
self.token = token
self._minted_at = datetime.now(UTC)
self.token_expiry = self._parse_token_expiry(payload)
+ # Capture a rotated refresh token without mutating self.refresh_token: a single-use grant
+ # must keep using the original token to mint within this run, while a caller with a DB row
+ # persists the rotated one for the next sync. Only a non-empty string counts as a rotation.
+ rotated = payload.get("refresh_token")
+ if isinstance(rotated, str) and rotated:
+ self.rotated_refresh_token = rotated
def _parse_token_expiry(self, payload: dict[str, Any]) -> datetime:
now = datetime.now(UTC)
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 334d9f3cc7a0..3282e3a29e4a 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
@@ -54,6 +54,8 @@ class TestOAuth2Auth(SimpleTestCase):
# The token is cached for the run — a second request mints nothing new.
assert _apply_auth(auth) == "Bearer minted-123"
assert mock_session.return_value.post.call_count == 1
+ # 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_refresh_token_grant_body_and_no_in_memory_rotation(self, mock_session):
@@ -72,9 +74,12 @@ class TestOAuth2Auth(SimpleTestCase):
assert body["grant_type"] == "refresh_token"
assert body["refresh_token"] == "refresh-orig"
# The auth object never rotates its in-memory refresh token, even when the response
- # returns a new one — rotation writeback is a Phase 2 sync-activity concern, not the
- # auth object's. Mutating it here would silently diverge from the persisted value.
+ # returns a new one — it must keep minting with the original this run. Mutating it here
+ # would silently diverge from the persisted value.
assert auth.refresh_token == "refresh-orig"
+ # The rotated token is captured separately so a caller holding a DB row can persist it for
+ # the next sync (the rotating-provider writeback this enables — e.g. Calendly).
+ assert auth.rotated_refresh_token == "refresh-rotated"
@patch(f"{AUTH_MODULE}.make_tracked_session")
def test_remints_when_expired_and_reuses_when_fresh(self, mock_session):
diff --git a/products/warehouse_sources/backend/tests/test_custom_oauth2_integration.py b/products/warehouse_sources/backend/tests/test_custom_oauth2_integration.py
new file mode 100644
index 000000000000..cafea2e662d7
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/test_custom_oauth2_integration.py
@@ -0,0 +1,217 @@
+import json
+from datetime import UTC, datetime, timedelta
+from typing import Any, Optional
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.contrib.admin.sites import AdminSite
+from django.db import IntegrityError
+
+from posthog.models import Team
+from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED
+from posthog.models.scoping.manager import TeamScopeError
+
+from products.warehouse_sources.backend.admin.custom_oauth2_integration_admin import CustomOAuth2IntegrationAdmin
+from products.warehouse_sources.backend.models.custom_oauth2_integration import (
+ CustomOAuth2Integration,
+ custom_oauth2_refresh_counter,
+ get_custom_oauth2_integration,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (
+ OAuth2AuthRequestError,
+)
+
+AUTH_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth"
+
+
+def _token_response(status_code: int = 200, payload: Optional[dict[str, Any]] = 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
+
+
+class TestCustomOAuth2Integration(BaseTest):
+ def _make_integration(
+ self,
+ *,
+ team: Optional[Team] = None,
+ config: Optional[dict[str, Any]] = None,
+ sensitive_config: Optional[dict[str, Any]] = None,
+ ) -> CustomOAuth2Integration:
+ team = team or self.team
+ base_config = {"token_url": "https://auth.example.com/token", "client_id": "cid", "grant_type": "refresh_token"}
+ base_secrets = {"client_secret": "csecret", "refresh_token": "refresh-orig"}
+ return CustomOAuth2Integration.objects.for_team(team.pk).create(
+ team=team,
+ config={**base_config, **(config or {})},
+ sensitive_config={**base_secrets, **(sensitive_config or {})},
+ )
+
+ def _reload(self, integration: CustomOAuth2Integration) -> CustomOAuth2Integration:
+ # The fail-closed manager rejects refresh_from_db() (no team context in a plain test), so re-fetch
+ # through for_team to prove the values actually hit the DB rather than only the in-memory instance.
+ return CustomOAuth2Integration.objects.for_team(integration.team_id).get(pk=integration.pk)
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_refresh_and_persist_writes_rotated_refresh_token(self, mock_session):
+ # The Calendly bug this model exists to fix: the provider rotates the single-use refresh token on
+ # every mint, so the new one must be persisted or the next sync fails with invalid_grant.
+ mock_session.return_value.post.return_value = _token_response(
+ payload={"access_token": "minted-1", "expires_in": 3600, "refresh_token": "refresh-rotated"}
+ )
+ integration = self._make_integration()
+
+ token = integration.refresh_and_persist()
+
+ assert token == "minted-1"
+ fresh = self._reload(integration)
+ assert fresh.sensitive_config["refresh_token"] == "refresh-rotated"
+ assert fresh.sensitive_config["access_token"] == "minted-1"
+ assert fresh.sensitive_config["token_expiry"] is not None
+ assert fresh.config["refreshed_at"] > 0
+ assert fresh.errors == ""
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_refresh_and_persist_keeps_refresh_token_when_not_rotated(self, mock_session):
+ # A non-rotating provider returns no refresh_token in the response; the stored one must survive
+ # untouched (a stray overwrite to None would break the next refresh).
+ mock_session.return_value.post.return_value = _token_response(
+ payload={"access_token": "minted-2", "expires_in": 3600}
+ )
+ integration = self._make_integration()
+
+ integration.refresh_and_persist()
+
+ fresh = self._reload(integration)
+ assert fresh.sensitive_config["refresh_token"] == "refresh-orig"
+ assert fresh.sensitive_config["access_token"] == "minted-2"
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_refresh_and_persist_marks_error_and_preserves_token_on_failure(self, mock_session):
+ # A token-endpoint rejection (e.g. an expired refresh token) must surface the broken-token state
+ # via errors without clobbering the stored refresh token — re-entry replaces it later.
+ mock_session.return_value.post.return_value = _token_response(
+ status_code=400, payload={"error": "invalid_grant", "error_description": "expired"}
+ )
+ integration = self._make_integration()
+
+ with self.assertRaises(OAuth2AuthRequestError):
+ integration.refresh_and_persist()
+
+ fresh = self._reload(integration)
+ assert fresh.errors == ERROR_TOKEN_REFRESH_FAILED
+ assert fresh.sensitive_config["refresh_token"] == "refresh-orig"
+ assert "access_token" not in fresh.sensitive_config
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_get_access_token_reuses_valid_cached_token_without_minting(self, mock_session):
+ # The reuse gate: a still-valid cached token is returned as-is, minting nothing. This is what
+ # caps refresh-token rotation churn for high-frequency syncs.
+ future = (datetime.now(UTC) + timedelta(hours=1)).isoformat()
+ integration = self._make_integration(sensitive_config={"access_token": "cached-token", "token_expiry": future})
+
+ assert integration.get_access_token() == "cached-token"
+ mock_session.return_value.post.assert_not_called()
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_get_access_token_refreshes_expired_cached_token(self, mock_session):
+ # The other side of the gate: a stale cached token forces a fresh mint, which is persisted.
+ mock_session.return_value.post.return_value = _token_response(
+ payload={"access_token": "minted-fresh", "expires_in": 3600}
+ )
+ past = (datetime.now(UTC) - timedelta(hours=1)).isoformat()
+ integration = self._make_integration(sensitive_config={"access_token": "stale-token", "token_expiry": past})
+
+ assert integration.get_access_token() == "minted-fresh"
+ mock_session.return_value.post.assert_called_once()
+ assert self._reload(integration).sensitive_config["access_token"] == "minted-fresh"
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_refresh_increments_success_and_failure_counters(self, mock_session):
+ # The refresh path mirrors core OauthIntegration.refresh_access_token's observability: a
+ # success/failed counter so a stuck rotating provider shows up in metrics, not just logs.
+ success_before = custom_oauth2_refresh_counter.labels("success")._value.get()
+ failed_before = custom_oauth2_refresh_counter.labels("failed")._value.get()
+
+ mock_session.return_value.post.return_value = _token_response(
+ payload={"access_token": "minted", "expires_in": 3600}
+ )
+ self._make_integration().refresh_and_persist()
+
+ mock_session.return_value.post.return_value = _token_response(
+ status_code=400, payload={"error": "invalid_grant"}
+ )
+ with self.assertRaises(OAuth2AuthRequestError):
+ self._make_integration().refresh_and_persist()
+
+ assert custom_oauth2_refresh_counter.labels("success")._value.get() == success_before + 1
+ assert custom_oauth2_refresh_counter.labels("failed")._value.get() == failed_before + 1
+
+ @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.
+ now = datetime.now(UTC)
+ integration = self._make_integration(
+ config={"refreshed_at": int(now.timestamp())},
+ sensitive_config={
+ "access_token": "short-lived",
+ "token_expiry": (now + timedelta(seconds=30)).isoformat(),
+ },
+ )
+
+ assert integration.get_access_token() == "short-lived"
+ mock_session.return_value.post.assert_not_called()
+
+ def test_constraint_rejects_duplicate_non_null_source_link(self):
+ # The partial unique index: a second integration for the same (team, source) must be rejected.
+ from products.warehouse_sources.backend.models import ExternalDataSource # noqa: PLC0415
+
+ source = ExternalDataSource.objects.create(
+ team=self.team, source_id="sid", connection_id="cid", status="Completed", source_type="Stripe"
+ )
+ CustomOAuth2Integration.objects.for_team(self.team.pk).create(team=self.team, external_data_source=source)
+
+ with self.assertRaises(IntegrityError):
+ CustomOAuth2Integration.objects.for_team(self.team.pk).create(team=self.team, external_data_source=source)
+
+ def test_constraint_allows_multiple_null_source_rows(self):
+ # The condition excludes NULL source links, so unlinked rows (pre-create token stores) don't
+ # collide — the plain UniqueConstraint would also allow this, but only by accident of NULL
+ # distinctness; this pins the intended behaviour.
+ self._make_integration()
+ self._make_integration() # would raise without the partial condition only if NULLs collided
+
+ assert (
+ CustomOAuth2Integration.objects.for_team(self.team.pk).filter(external_data_source__isnull=True).count()
+ == 2
+ )
+
+ def test_team_scoping_is_fail_closed(self):
+ integration = self._make_integration()
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ other_integration = self._make_integration(team=other_team)
+
+ # No team context set → the fail-closed manager refuses to return rows.
+ with self.assertRaises(TeamScopeError):
+ CustomOAuth2Integration.objects.get(pk=integration.pk)
+
+ # The helper scopes to a team and never crosses to another team's row.
+ assert get_custom_oauth2_integration(str(integration.pk), self.team.pk).pk == integration.pk
+ with self.assertRaises(CustomOAuth2Integration.DoesNotExist):
+ get_custom_oauth2_integration(str(other_integration.pk), self.team.pk)
+
+ def test_admin_get_queryset_reads_outside_team_scope(self):
+ # Django admin runs outside request/team scope, so the model's fail-closed default manager would
+ # raise TeamScopeError the moment the changelist evaluates the queryset. The admin's get_queryset()
+ # reads through unscoped() instead; this guards against that escape hatch being dropped.
+ integration = self._make_integration()
+ admin_instance = CustomOAuth2IntegrationAdmin(CustomOAuth2Integration, AdminSite())
+
+ rows = list(admin_instance.get_queryset(MagicMock()))
+
+ assert integration.pk in {row.pk for row in rows}