Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): backfill and reconcile source credential integrations (#124115)

Tom Owers486787354c66
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.md
index 589cceade2a1..71594b6c26c8 100644
--- a/.agents/skills/implementing-warehouse-sources/SKILL.md
+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md
@@ -421,6 +421,8 @@ Override `credential_kind` in your `source.py` when the default is wrong:
A subclass inherits the override of its parent, so a subclass of an overriding source sets its own kind (`NeonSource` returns `neon`, not the `postgresql` of `PostgresSource`).
+The `reconcile_warehouse_source_credentials` command checks that each `*_integration_id` field and each `credentials_integration_id` column points at an `Integration` row. When your source keeps its OAuth rows in another model, override `integration_id_fields_point_at_integrations` to return `False` (`CustomSource` does this).
+
The result is frozen in the generated file `facade/credential_kinds.py` (`CREDENTIAL_KINDS`), because a kind is stored data. Never change the kind of a released source. A test fails when the file is out of date, when a kind is longer than 32 characters, or when two source types share a kind.
Each credential kind also has a default auth type: the `credential_auth_type` property on the source class. The default on `BaseSource` (`derive_credential_auth_type` in `products/warehouse_sources/sources/common/credential_auth_type.py`) reads the connection fields:
@@ -461,7 +463,7 @@ A source's typed-in connection fields go to one `Integration` row of the source'
- The row has the auth type that `facade/credential_auth_types.py` derives for the kind (`token` or `credentials`). An OAuth-only source has no typed-in row. On a catalogue kind with an OAuth default, the row has a second auth type of that kind (`stripe` `token`, `github` `token`). The catalogue entry of the kind (`posthog/integrations/catalogue.py`) must support the derived auth type. If it does not, add the type there and run `hogli build:projections --only integration-kinds`. The test `test_every_typed_in_source_type_has_an_auth_type_its_kind_supports` fails otherwise.
- The row has the marker `config["warehouse_source_type"]`. The SDK writes the marker only through `IntegrationManager.source(kind)`, and the named accessors (`IntegrationManager.stripe.token`) and kind-limited pickers skip marked rows. Hog functions can never use a marked row as an input.
- Rows are visible in the integrations list with their auth type, and several sources can use one row. An edit of a shared row raises `SharedCredentialsError` unless the caller confirms. An edit of an identifying field of a shared row makes a new row. The source gives these fields with the `credential_identity_fields` property on its class. The default is `connection_host_fields` plus each generic name in `GENERIC_IDENTITY_FIELDS` (`host`, `port`, `instance_url`, `connection_string`, `ssh_tunnel`, `user`, `username`, `account`, `account_id`, `account_sid`) that the source declares, at any depth (Snowflake keeps `user` under `auth_type`). The compare skips the secrets inside `connection_string` (it reads the scheme, user, hosts and database) and inside `ssh_tunnel` (it reads `enabled`, `host`, `port` and the username), so a secret rotation asks for a confirmation and does not make a new row. Override the property in your `source.py` only when a different field says where the credentials connect, or as which account.
-- The store never deletes a row. When a source is soft deleted, the store only releases the row. A row that nothing uses stays in the integrations list.
+- The store never deletes a row. A soft delete of a source does not read or change its row. A row that nothing uses stays in the integrations list.
- `products/warehouse_sources/backend/integration_usages.py` reports each source that points at a row, with its `credentials_integration_id` column (one indexed query) or a `*_integration_id` field in its inputs. A source whose inputs do not decode counts as a user of every OAuth row of its credential kind, with the usage type `unreadable_warehouse_source`, but not of a typed-in row, because the column always reads. Such a user blocks a delete only. It does not make an edit of the row shared. The SDK reads the usages for `usages`, and `delete` raises `IntegrationInUse` while a source uses the row. The integrations API returns that as a 400.
- Never query these rows in source code, and do not call the credentials store from source code. Use `SourceInputsStore`, which will use the credentials store internally. The Custom source keeps its `job_inputs` as they are.
- When the team has the `warehouse-source-credentials-dual-write` flag, `save`, `asave`, `assign` and `create` keep the `credentials_integration_id` column in step with the inputs they write. The column holds the one row that the source uses:
diff --git a/products/warehouse_sources/backend/logic/source_credentials.py b/products/warehouse_sources/backend/logic/source_credentials.py
index 0fe3ec12bc8f..58f7b4f98054 100644
--- a/products/warehouse_sources/backend/logic/source_credentials.py
+++ b/products/warehouse_sources/backend/logic/source_credentials.py
@@ -26,7 +26,6 @@ from urllib.parse import parse_qsl, unquote, urlsplit
from uuid import UUID, uuid4
import structlog
-from prometheus_client import Counter
from posthog.dataclasses import frozen
from posthog.helpers.encrypted_fields import FERNET_TOKEN_PREFIX, EncryptedJSONField
@@ -51,11 +50,6 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
logger = structlog.get_logger(__name__)
-CREDENTIALS_ORPHANED_COUNTER = Counter(
- "warehouse_source_credentials_orphaned_total",
- "Credentials rows that no object uses any more after a warehouse source released them",
-)
-
# Decrypts leaves with the same keys as `Integration.sensitive_config`. The keys come from the settings.
_SENSITIVE_CONFIG_FIELD = EncryptedJSONField(default=dict, ignore_decrypt_errors=True)
@@ -223,26 +217,6 @@ class WarehouseSourceCredentialsStore:
except IntegrationNotFound:
return []
- @staticmethod
- def release(source: ExternalDataSource) -> bool:
- """Note that the source no longer uses its row. Returns True when nothing else uses it.
-
- The row stays, because a person may reuse it or delete it from the integrations list.
- """
- pk = _pk(source)
- rows = _accessor_or_none(source)
- if pk is None or rows is None:
- return False
- try:
- others = _other_usages(rows, source, pk)
- except IntegrationNotFound:
- return False
- if others:
- return False
- CREDENTIALS_ORPHANED_COUNTER.inc()
- logger.info("warehouse_source_credentials_orphaned", team_id=source.team_id, integration_id=pk)
- return True
-
@staticmethod
def discard(source: ExternalDataSource) -> bool:
"""Delete the row of a source whose create did not finish. Returns True when it deleted the row.
@@ -445,6 +419,12 @@ def _fields_of(sensitive_config: Any) -> dict[str, Any] | None:
# The field encrypts each leaf, and a leaf that fails to decrypt comes back as raw ciphertext
# rather than raising. Peel extra layers a read-then-save added, and treat any leaf no key can
# open as an unreadable row, so ciphertext is never handed out as a credential.
+ return recover_encrypted_leaves(fields)
+
+
+def recover_encrypted_leaves(fields: Mapping[str, Any]) -> dict[str, Any] | None:
+ """``fields`` with every ciphertext leaf decrypted through all its layers, or None when a leaf
+ cannot be opened by any configured key."""
try:
return _recover_leaves(dict(fields))
except _UndecryptableLeaf:
diff --git a/products/warehouse_sources/backend/logic/source_credentials_rollout.py b/products/warehouse_sources/backend/logic/source_credentials_rollout.py
index 063b1025060b..00d3b8acf771 100644
--- a/products/warehouse_sources/backend/logic/source_credentials_rollout.py
+++ b/products/warehouse_sources/backend/logic/source_credentials_rollout.py
@@ -59,7 +59,10 @@ if TYPE_CHECKING:
from products.warehouse_sources.backend.temporal.data_imports.sources.common.job_input_classification import (
SplitJobInputs,
)
- from products.warehouse_sources.backend.temporal.data_imports.sources.common.oauth_pointers import OAuthPointer
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.oauth_pointers import (
+ OAuthPointer,
+ PointerPath,
+ )
logger = structlog.get_logger(__name__)
@@ -692,6 +695,25 @@ def _source_class(source_type: str) -> Any:
return SourceRegistry.get_source(ExternalDataSourceType(source_type))
+def connection_fields_equal(left: Mapping[str, Any], right: Mapping[str, Any]) -> bool:
+ """True when two connection field mappings hold the same stored values."""
+ return same_connection_fields(left, right)
+
+
+def split_connection_fields(source_type: str, inputs: Mapping[str, Any]) -> dict[str, Any]:
+ """The connection fields of ``inputs``, which a credentials row holds."""
+ return _connection_fields(source_type, inputs)
+
+
+def in_use_oauth_slot(source_type: str, inputs: Mapping[str, Any]) -> "PointerPath | None":
+ """Where ``inputs`` keep the OAuth pointer that the sync uses. See `_BaseSource.in_use_oauth_slot`.
+
+ Raises ValueError for an unknown source type, and `OAuthPointerShapeError` (a ValueError) when the inputs
+ cannot tell which OAuth field is in use.
+ """
+ return _source_class(source_type).in_use_oauth_slot(inputs)
+
+
def _in_event_loop() -> bool:
try:
asyncio.get_running_loop()
diff --git a/products/warehouse_sources/backend/logic/source_credentials_sync.py b/products/warehouse_sources/backend/logic/source_credentials_sync.py
new file mode 100644
index 000000000000..629a2ece9061
--- /dev/null
+++ b/products/warehouse_sources/backend/logic/source_credentials_sync.py
@@ -0,0 +1,502 @@
+"""Backfill the credentials references of warehouse sources, and report references that point at no row.
+
+The backfill fills each source's `credentials_integration_id` column with the one row the source uses:
+
+- A source with typed-in credentials: the backfill copies the connection fields of its stored `job_inputs` to
+ its row. A source without a reference gets one new row. A source with a reference gets an update of that
+ row, so a run can be repeated. The backfill never merges two sources into one row, because that would put
+ the secrets of both under one edit point.
+- An OAuth source: the column gets the in-use `*_integration_id` pointer of its stored `job_inputs`.
+
+Old rows can hold shapes that the OAuth walk does not read (a flat legacy key, a select stored as a string).
+The backfill logs and skips them. It never guesses which pointer is in use.
+
+The reconciler only reports. It lists each reference that points at no row, and each OAuth source whose
+column differs from its in-use pointer. It never deletes a row: a row that nothing uses stays in the
+integrations list.
+"""
+
+from collections import Counter
+from collections.abc import Callable, Iterable, Mapping, Sequence
+from typing import Any
+from uuid import UUID
+
+from django.db import transaction
+
+import structlog
+
+from posthog.dataclasses import frozen
+from posthog.integrations import IntegrationManager, IntegrationReference
+
+from products.warehouse_sources.backend.facade.contracts import SharedCredentialsError, UnreadableSourceInputsError
+from products.warehouse_sources.backend.logic.credential_auth_types import has_typed_in_credentials
+from products.warehouse_sources.backend.logic.source_credentials import (
+ CredentialsNotFoundError,
+ CredentialsUnreadable,
+ WarehouseSourceCredentialsStore,
+ recover_encrypted_leaves,
+)
+from products.warehouse_sources.backend.logic.source_credentials_rollout import (
+ connection_fields_equal,
+ in_use_oauth_slot,
+ split_connection_fields,
+)
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.oauth_pointers import (
+ OAuthPointerShapeError,
+ PointerPath,
+ pointer_at,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+logger = structlog.get_logger(__name__)
+
+CREATED = "created"
+UPDATED = "updated"
+RECREATED = "recreated"
+UNCHANGED = "unchanged"
+OAUTH_LINKED = "oauth_linked"
+SKIPPED_SHAPE = "skipped_unreadable_shape"
+SKIPPED_NO_ROW = "skipped_no_row"
+SKIPPED_SHARED = "skipped_shared"
+SKIPPED_DELETED = "skipped_deleted"
+SKIPPED_UNREADABLE = "skipped_unreadable"
+SKIPPED_UNKNOWN_TYPE = "skipped_unknown_type"
+FAILED = "failed"
+
+# The outcomes of a source whose row does not hold its stored connection fields yet.
+NOT_BACKFILLED = frozenset(
+ {
+ CREATED,
+ UPDATED,
+ RECREATED,
+ OAUTH_LINKED,
+ SKIPPED_SHARED,
+ SKIPPED_UNREADABLE,
+ SKIPPED_SHAPE,
+ SKIPPED_UNKNOWN_TYPE,
+ FAILED,
+ }
+)
+
+POINTER_SUFFIX = "_integration_id"
+# The key under which reports name the reference column.
+COLUMN_KEY = "credentials_integration_id"
+
+# Counts keyed by (source_type, outcome).
+BackfillCounts = Counter[tuple[str, str]]
+
+
+@frozen
+class DanglingReference:
+ """A reference in a source's inputs that points at no row the source can use."""
+
+ team_id: int
+ source_id: str
+ source_type: str
+ key: str
+ integration_id: str
+
+
+@frozen
+class ReferenceMismatch:
+ """An OAuth source whose reference column differs from the in-use pointer of its inputs."""
+
+ team_id: int
+ source_id: str
+ source_type: str
+ path: str
+ column: str | None
+ pointer: str
+
+
+@frozen
+class ReconcileResult:
+ scanned: int
+ references: int
+ dangling: tuple[DanglingReference, ...]
+ mismatched: tuple[ReferenceMismatch, ...] = ()
+
+
+def backfill_source_credentials(
+ *,
+ execute: bool,
+ batch_size: int = 200,
+ team_ids: Sequence[int] = (),
+ source_type: str | None = None,
+ limit: int | None = None,
+ on_batch: Callable[[int], None] | None = None,
+) -> BackfillCounts:
+ """Make the reference column of each non-deleted source point at the row it uses. A source with typed-in
+ credentials gets a row that holds the connection fields of its stored `job_inputs`. An OAuth source gets
+ the in-use OAuth pointer of its stored `job_inputs` in its column.
+
+ With ``execute`` false the function only counts what it would do. Sources are read in id order, so a
+ run can be repeated and a crash loses nothing.
+ """
+ counts: BackfillCounts = Counter()
+ for batch in _batches(batch_size, team_ids, source_type, limit):
+ _process_batch(batch, execute, counts)
+ if on_batch:
+ on_batch(len(batch))
+ return counts
+
+
+def reconcile_credential_references(
+ *, batch_size: int = 500, team_ids: Sequence[int] = (), source_type: str | None = None
+) -> ReconcileResult:
+ """Find each reference of non-deleted sources that points at no row, and each OAuth source whose column
+ differs from the in-use pointer of its inputs.
+
+ The column of a source with typed-in credentials must point at a warehouse source row that the source can
+ use. The column of an OAuth source, and each OAuth reference (`*_integration_id`) in the inputs, must point
+ at a row of the source's team.
+ """
+ scanned = references = 0
+ dangling: list[DanglingReference] = []
+ mismatched: list[ReferenceMismatch] = []
+ for batch in _batches(batch_size, team_ids, source_type, None):
+ scanned += len(batch)
+ found = _references_in_batch(batch)
+ references += found.references
+ dangling.extend(found.dangling)
+ mismatched.extend(found.mismatched)
+ return ReconcileResult(
+ scanned=scanned, references=references, dangling=tuple(dangling), mismatched=tuple(mismatched)
+ )
+
+
+def _batches(
+ batch_size: int, team_ids: Sequence[int], source_type: str | None, limit: int | None
+) -> Iterable[list[ExternalDataSource]]:
+ last_id: UUID | None = None
+ remaining = limit
+ while remaining is None or remaining > 0:
+ page_size = batch_size if remaining is None else min(batch_size, remaining)
+ batch = _next_sources(last_id, page_size, team_ids, source_type)
+ if not batch:
+ return
+ last_id = batch[-1].id
+ yield batch
+ if remaining is not None:
+ remaining -= len(batch)
+
+
+def _next_sources(
+ after_id: UUID | None, size: int, team_ids: Sequence[int], source_type: str | None
+) -> list[ExternalDataSource]:
+ # `select_related(None)` clears the default manager's join, which `only()` cannot defer past.
+ queryset = (
+ ExternalDataSource.objects.exclude(deleted=True)
+ .select_related(None)
+ .only("id", "team_id", "source_type", "job_inputs", "credentials_integration_id")
+ .order_by("id")
+ )
+ if after_id is not None:
+ queryset = queryset.filter(id__gt=after_id)
+ if team_ids:
+ queryset = queryset.filter(team_id__in=list(team_ids))
+ if source_type:
+ queryset = queryset.filter(source_type=source_type)
+ return list(queryset[:size])
+
+
+def _process_batch(batch: Iterable[ExternalDataSource], execute: bool, counts: BackfillCounts) -> None:
+ planned: list[tuple[ExternalDataSource, dict[str, Any]]] = []
+ for source in batch:
+ source_type = str(source.source_type)
+ try:
+ plan = _plan(source)
+ except UnreadableSourceInputsError:
+ counts[(source_type, SKIPPED_UNREADABLE)] += 1
+ continue
+ except OAuthPointerShapeError:
+ _log_shape(source)
+ counts[(source_type, SKIPPED_SHAPE)] += 1
+ continue
+ except ValueError:
+ counts[(source_type, SKIPPED_UNKNOWN_TYPE)] += 1
+ continue
+ if plan == OAUTH_LINKED:
+ _run(source, execute, plan, counts)
+ continue
+ if isinstance(plan, str):
+ counts[(source_type, plan)] += 1
+ continue
+ planned.append((source, plan))
+ if not planned:
+ return
+
+ stored = WarehouseSourceCredentialsStore.get_many(source for source, _ in planned)
+ for source, fields in planned:
+ existing = stored.get(source.id)
+ if source.credentials_integration_id is None:
+ outcome = CREATED
+ elif existing is None:
+ outcome = RECREATED
+ elif isinstance(existing, CredentialsUnreadable) or not connection_fields_equal(existing, fields):
+ outcome = UPDATED
+ else:
+ counts[(str(source.source_type), UNCHANGED)] += 1
+ continue
+ _run(source, execute, outcome, counts)
+
+
+def _plan(source: ExternalDataSource) -> dict[str, Any] | str:
+ """The connection fields that the row of a source with typed-in credentials must hold, or the outcome of
+ a source that needs no row write (an OAuth source, a source without connection fields)."""
+ inputs = SourceInputsStore.load_stored(source)
+ slot = in_use_oauth_slot(str(source.source_type), inputs)
+ if slot is not None:
+ return _oauth_outcome(source, inputs, slot)
+ fields = _stored_connection_fields(source, inputs)
+ if not fields or not has_typed_in_credentials(str(source.source_type)):
+ return SKIPPED_NO_ROW
+ return fields
+
+
+def _oauth_outcome(source: ExternalDataSource, inputs: Mapping[str, Any], slot: PointerPath) -> str:
+ pointer = pointer_at(inputs, slot)
+ if pointer is None:
+ # The inputs hold no pointer, so they cannot tell the row. A column that a later step filled stays.
+ return SKIPPED_NO_ROW
+ if source.credentials_integration_id == str(IntegrationReference.from_legacy_id(pointer.integration_id)):
+ return UNCHANGED
+ return OAUTH_LINKED
+
+
+def _run(source: ExternalDataSource, execute: bool, outcome: str, counts: BackfillCounts) -> None:
+ if execute:
+ try:
+ outcome = _sync_source(source)
+ except OAuthPointerShapeError:
+ _log_shape(source)
+ outcome = SKIPPED_SHAPE
+ except Exception:
+ logger.exception("warehouse_source_credentials.backfill_failed", source_id=str(source.id))
+ outcome = FAILED
+ counts[(str(source.source_type), outcome)] += 1
+
+
+def _log_shape(source: ExternalDataSource) -> None:
+ logger.warning(
+ "warehouse_source_credentials.backfill_skipped_unreadable_shape",
+ source_id=str(source.id),
+ team_id=source.team_id,
+ source_type=str(source.source_type),
+ )
+
+
+def _stored_connection_fields(source: ExternalDataSource, inputs: Mapping[str, Any]) -> dict[str, Any]:
+ """The connection fields of the stored `job_inputs`. A leaf that no key can decrypt raises
+ `UnreadableSourceInputsError`, so its ciphertext never goes to a row."""
+ fields = split_connection_fields(str(source.source_type), inputs)
+ recovered = recover_encrypted_leaves(fields)
+ if recovered is None:
+ raise UnreadableSourceInputsError(f"job_inputs of source {source.id} hold an undecryptable value")
+ return recovered
+
+
+def _sync_source(source: ExternalDataSource) -> str:
+ """Write the reference (and for typed-in credentials the row) of one source from its stored `job_inputs`,
+ read again under the source lock.
+
+ The lock order (source, then row) is the order of the dual write. A dual write that changed the source
+ after the batch read has either committed, so this read sees its inputs and its column, or it waits for
+ this transaction. So the backfill never writes old fields, and never makes a second row.
+ """
+ with transaction.atomic():
+ fresh = (
+ ExternalDataSource.objects.select_related(None)
+ .select_for_update(of=("self",))
+ .only(
+ "id",
+ "team_id",
+ "source_type",
+ "job_inputs",
+ "credentials_integration_id",
+ "prefix",
+ "created_by_id",
+ "deleted",
+ )
+ .filter(pk=source.pk, team_id=source.team_id)
+ .exclude(deleted=True)
+ .first()
+ )
+ if fresh is None:
+ return SKIPPED_DELETED
+ inputs = SourceInputsStore.load_stored(fresh)
+ slot = in_use_oauth_slot(str(fresh.source_type), inputs)
+ if slot is not None:
+ outcome = _oauth_outcome(fresh, inputs, slot)
+ pointer = pointer_at(inputs, slot)
+ if outcome == OAUTH_LINKED and pointer is not None:
+ SourceInputsStore.write_credentials_reference(
+ fresh, IntegrationReference.from_legacy_id(pointer.integration_id)
+ )
+ return outcome
+ fields = _stored_connection_fields(fresh, inputs)
+ if not fields or not has_typed_in_credentials(str(fresh.source_type)):
+ return SKIPPED_NO_ROW
+ before = fresh.credentials_integration_id
+ if before is None:
+ SourceInputsStore.write_credentials_reference(fresh, WarehouseSourceCredentialsStore.create(fresh, fields))
+ return CREATED
+ try:
+ reference = WarehouseSourceCredentialsStore.update(fresh, fields)
+ except CredentialsNotFoundError:
+ SourceInputsStore.write_credentials_reference(fresh, WarehouseSourceCredentialsStore.create(fresh, fields))
+ return RECREATED
+ except SharedCredentialsError:
+ # Other objects use the row with other values. A person decides, so the backfill does not write.
+ return SKIPPED_SHARED
+ if str(reference) != before:
+ # A change of where a shared row connects made a new row for this source.
+ SourceInputsStore.write_credentials_reference(fresh, reference)
+ return UPDATED
+
+
+@frozen
+class _BatchReferences:
+ references: int
+ dangling: tuple[DanglingReference, ...]
+ mismatched: tuple[ReferenceMismatch, ...]
+
+
+def _references_in_batch(batch: Iterable[ExternalDataSource]) -> _BatchReferences:
+ typed_in: list[ExternalDataSource] = []
+ # (source, key, value) of each pointer that must name an OAuth row of the source's team, by team.
+ oauth: dict[int, list[tuple[ExternalDataSource, str, str]]] = {}
+ # Columns of sources whose inputs cannot tell the kind of row. Any row of the team satisfies them.
+ unknown: dict[int, list[tuple[ExternalDataSource, str, str]]] = {}
+ unresolvable: list[tuple[ExternalDataSource, str]] = []
+ mismatched: list[ReferenceMismatch] = []
+ for source in batch:
+ if not _pointers_are_integration_ids(str(source.source_type)):
+ continue
+ try:
+ inputs: Mapping[str, Any] | None = SourceInputsStore.load_stored(source)
+ except UnreadableSourceInputsError:
+ inputs = None
+ readable, slot = _read_slot(source, inputs)
+ column = source.credentials_integration_id
+ if column is not None:
+ if _column_pk(column) is None:
+ unresolvable.append((source, column))
+ elif not readable:
+ unknown.setdefault(source.team_id, []).append((source, COLUMN_KEY, column))
+ elif slot is None:
+ typed_in.append(source)
+ else:
+ oauth.setdefault(source.team_id, []).append((source, COLUMN_KEY, column))
+ if inputs is None:
+ continue
+ for pointer in _pointers(inputs):
+ oauth.setdefault(source.team_id, []).append((source, pointer.key, pointer.value))
+ in_use = pointer_at(inputs, slot) if slot is not None else None
+ if in_use is not None and column != str(IntegrationReference.from_legacy_id(in_use.integration_id)):
+ mismatched.append(
+ ReferenceMismatch(
+ team_id=source.team_id,
+ source_id=str(source.id),
+ source_type=str(source.source_type),
+ path=".".join(in_use.path),
+ column=column,
+ pointer=str(in_use.integration_id),
+ )
+ )
+
+ dangling: list[DanglingReference] = [_dangling(source, COLUMN_KEY, value) for source, value in unresolvable]
+ found = WarehouseSourceCredentialsStore.get_many(typed_in)
+ dangling.extend(
+ _dangling(source, COLUMN_KEY, str(source.credentials_integration_id))
+ for source in typed_in
+ if source.id not in found
+ )
+ for rows, by_team in ((IntegrationManager.any, oauth), (IntegrationManager.any.with_source_rows(), unknown)):
+ for team_id, pointers in by_team.items():
+ ids = {pk for _, key, value in pointers if (pk := _pointer_pk(key, value)) is not None}
+ existing = rows.get_many(team_id, ids)
+ dangling.extend(
+ _dangling(source, key, value)
+ for source, key, value in pointers
+ if _pointer_pk(key, value) not in existing
+ )
+ return _BatchReferences(
+ references=len(unresolvable)
+ + len(typed_in)
+ + sum(len(pointers) for by_team in (oauth, unknown) for pointers in by_team.values()),
+ dangling=tuple(dangling),
+ mismatched=tuple(mismatched),
+ )
+
+
+def _read_slot(source: ExternalDataSource, inputs: Mapping[str, Any] | None) -> tuple[bool, PointerPath | None]:
+ """Whether the inputs tell the kind of row the source uses, and the in-use OAuth field."""
+ if inputs is None:
+ return False, None
+ try:
+ return True, in_use_oauth_slot(str(source.source_type), inputs)
+ except ValueError:
+ # An unknown source type, or an old shape that the walk does not read.
+ return False, None
+
+
+def _column_pk(column: str) -> int | None:
+ try:
+ return IntegrationReference.parse(column).legacy_id
+ except ValueError:
+ return None
+
+
+def _pointer_pk(key: str, value: str) -> int | None:
+ return _column_pk(value) if key == COLUMN_KEY else _pk(value)
+
+
+def _pointers_are_integration_ids(source_type: str) -> bool:
+ # The registry loads every source, so keep it off this module's import path.
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import ( # noqa: PLC0415 — heavy import
+ SourceRegistry,
+ )
+
+ try:
+ return SourceRegistry.get_source(
+ ExternalDataSourceType(source_type)
+ ).integration_id_fields_point_at_integrations
+ except ValueError:
+ return True
+
+
+@frozen
+class _Pointer:
+ key: str
+ value: str
+
+
+def _pointers(inputs: Mapping[str, Any]) -> list[_Pointer]:
+ # Switch groups and select options nest their fields one level down.
+ pointers: list[_Pointer] = []
+ for key, value in inputs.items():
+ if isinstance(value, Mapping):
+ pointers.extend(_pointers(value))
+ elif key.endswith(POINTER_SUFFIX) and value not in (None, ""):
+ pointers.append(_Pointer(key=key, value=str(value)))
+ return pointers
+
+
+def _pk(value: str) -> int | None:
+ try:
+ return int(value)
+ except ValueError:
+ return None
+
+
+def _dangling(source: ExternalDataSource, key: str, value: str) -> DanglingReference:
+ return DanglingReference(
+ team_id=source.team_id,
+ source_id=str(source.id),
+ source_type=str(source.source_type),
+ key=key,
+ integration_id=value,
+ )
diff --git a/products/warehouse_sources/backend/logic/source_inputs.py b/products/warehouse_sources/backend/logic/source_inputs.py
index 536d0c7f4c61..eaf5a067990b 100644
--- a/products/warehouse_sources/backend/logic/source_inputs.py
+++ b/products/warehouse_sources/backend/logic/source_inputs.py
@@ -71,6 +71,25 @@ class SourceInputsStore:
instances add no query. Use it before a loop that calls `load` once per table of a source."""
preload_connection_fields(sources)
+ @staticmethod
+ def load_stored(source: ExternalDataSource) -> dict[str, Any]:
+ """The decoded `job_inputs` as stored, never merged with the credentials row.
+
+ Only a tool that copies or checks the stored data should use it, such as the backfill. Raises
+ `UnreadableSourceInputsError` like `load`.
+ """
+ return _decode(source.job_inputs)
+
+ @staticmethod
+ def write_credentials_reference(source: ExternalDataSource, reference: IntegrationReference | None) -> None:
+ """Point the source at a credentials row, and change nothing else.
+
+ Only a tool that links existing sources to their rows should use it, such as the backfill. It never
+ copies fields to the row, never changes `job_inputs`, and does not change `updated_at`.
+ """
+ source.credentials_integration_id = None if reference is None else str(reference)
+ source.save(update_fields=["credentials_integration_id"])
+
@staticmethod
def load_settings(source: ExternalDataSource) -> dict[str, Any]:
"""Only the sync settings and runtime state of the source, never a connection field.
diff --git a/products/warehouse_sources/backend/management/commands/_credentials_report.py b/products/warehouse_sources/backend/management/commands/_credentials_report.py
new file mode 100644
index 000000000000..c531551c646d
--- /dev/null
+++ b/products/warehouse_sources/backend/management/commands/_credentials_report.py
@@ -0,0 +1,14 @@
+from django.core.management.base import OutputWrapper
+
+from products.warehouse_sources.backend.logic.source_credentials_sync import BackfillCounts
+
+
+def print_backfill_counts(stdout: OutputWrapper, counts: BackfillCounts, labels: dict[str, str] | None = None) -> None:
+ """One line per source type and outcome, then totals. Prints counts only, never field values."""
+ labels = labels or {}
+ totals: dict[str, int] = {}
+ for (source_type, outcome), count in sorted(counts.items()):
+ name = labels.get(outcome, outcome)
+ stdout.write(f"{source_type}: {name}={count}")
+ totals[name] = totals.get(name, 0) + count
+ stdout.write("total: " + (" ".join(f"{name}={count}" for name, count in sorted(totals.items())) or "no sources"))
diff --git a/products/warehouse_sources/backend/management/commands/backfill_warehouse_source_credentials.py b/products/warehouse_sources/backend/management/commands/backfill_warehouse_source_credentials.py
new file mode 100644
index 000000000000..c12c5ac9ebad
--- /dev/null
+++ b/products/warehouse_sources/backend/management/commands/backfill_warehouse_source_credentials.py
@@ -0,0 +1,42 @@
+"""Copy the connection fields of existing warehouse sources into their credentials rows."""
+
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+
+from products.warehouse_sources.backend.logic.source_credentials_sync import backfill_source_credentials
+from products.warehouse_sources.backend.management.commands._credentials_report import print_backfill_counts
+
+
+class Command(BaseCommand):
+ help = (
+ "Create or update the credentials row of each non-deleted warehouse source with typed-in credentials from "
+ "its stored job_inputs, and store the reference to a new row in job_inputs. A source with an OAuth "
+ "connection gets no row. Previews by default; pass --execute to write. Safe to repeat. Never prints "
+ "field values."
+ )
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--execute", action="store_true", help="Write rows. Without it the command only counts.")
+ parser.add_argument("--team-id", type=int, action="append", default=[], help="Only this team. Repeatable.")
+ parser.add_argument("--source-type", default=None, help="Only sources of this type, such as Postgres.")
+ parser.add_argument("--batch-size", type=int, default=200, help="Sources per batch.")
+ parser.add_argument("--limit", type=int, default=None, help="Stop after this many sources.")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ if options["batch_size"] < 1:
+ raise CommandError("--batch-size must be at least 1")
+ if options["limit"] is not None and options["limit"] < 0:
+ raise CommandError("--limit must be zero or greater")
+ execute: bool = options["execute"]
+
+ counts = backfill_source_credentials(
+ execute=execute,
+ batch_size=options["batch_size"],
+ team_ids=options["team_id"],
+ source_type=options["source_type"],
+ limit=options["limit"],
+ on_batch=lambda size: self.stdout.write(f"processed {size} sources"),
+ )
+ self.stdout.write(self.style.SUCCESS("Executed" if execute else "Dry run: nothing was written"))
+ print_backfill_counts(self.stdout, counts)
diff --git a/products/warehouse_sources/backend/management/commands/reconcile_warehouse_source_credentials.py b/products/warehouse_sources/backend/management/commands/reconcile_warehouse_source_credentials.py
new file mode 100644
index 000000000000..f3d2ceaaaba4
--- /dev/null
+++ b/products/warehouse_sources/backend/management/commands/reconcile_warehouse_source_credentials.py
@@ -0,0 +1,79 @@
+"""Report warehouse source references that point at no row or differ from the inputs, and verify that sources
+are backfilled."""
+
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+
+from products.warehouse_sources.backend.logic.source_credentials_sync import (
+ CREATED,
+ NOT_BACKFILLED,
+ OAUTH_LINKED,
+ RECREATED,
+ UPDATED,
+ backfill_source_credentials,
+ reconcile_credential_references,
+)
+from products.warehouse_sources.backend.management.commands._credentials_report import print_backfill_counts
+
+VERIFY_LABELS = {
+ CREATED: "missing_reference",
+ RECREATED: "missing_row",
+ UPDATED: "differs_or_unreadable_row",
+ OAUTH_LINKED: "oauth_reference_not_in_column",
+}
+
+
+class Command(BaseCommand):
+ help = (
+ "List each reference of non-deleted warehouse sources (the credentials_integration_id column and the "
+ "*_integration_id inputs) that points at no row, and each OAuth source whose column differs from its "
+ "in-use pointer. With --verify, also report sources whose row is missing or differs from job_inputs, and "
+ "fail when any source is not clean. Never writes and never deletes a row. Never prints field values."
+ )
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--verify", action="store_true", help="Also report sources that are not backfilled.")
+ parser.add_argument("--team-id", type=int, action="append", default=[], help="Only this team. Repeatable.")
+ parser.add_argument("--source-type", default=None, help="Only sources of this type, such as Postgres.")
+ parser.add_argument("--batch-size", type=int, default=500, help="Sources per batch.")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ if options["batch_size"] < 1:
+ raise CommandError("--batch-size must be at least 1")
+
+ result = reconcile_credential_references(
+ batch_size=options["batch_size"], team_ids=options["team_id"], source_type=options["source_type"]
+ )
+ for ref in result.dangling:
+ self.stdout.write(
+ f"dangling: team={ref.team_id} source={ref.source_id} type={ref.source_type} "
+ f"key={ref.key} integration={ref.integration_id}"
+ )
+ for mismatch in result.mismatched:
+ self.stdout.write(
+ f"mismatched: team={mismatch.team_id} source={mismatch.source_id} type={mismatch.source_type} "
+ f"path={mismatch.path} column={mismatch.column} pointer={mismatch.pointer}"
+ )
+ self.stdout.write(
+ f"scanned={result.scanned} references={result.references} dangling={len(result.dangling)} "
+ f"mismatched={len(result.mismatched)}"
+ )
+ if not options["verify"]:
+ return
+
+ counts = backfill_source_credentials(
+ execute=False,
+ batch_size=options["batch_size"],
+ team_ids=options["team_id"],
+ source_type=options["source_type"],
+ )
+ print_backfill_counts(self.stdout, counts, VERIFY_LABELS)
+ not_clean = sum(count for (_, outcome), count in counts.items() if outcome in NOT_BACKFILLED)
+ if not_clean or result.dangling or result.mismatched:
+ raise CommandError(
+ f"{not_clean} sources are not backfilled, {len(result.dangling)} references point at no row and "
+ f"{len(result.mismatched)} columns differ from the inputs. Run backfill_warehouse_source_credentials "
+ "--execute, then check the dangling references and the skipped shapes."
+ )
+ self.stdout.write(self.style.SUCCESS("Verified: every source has a matching row"))
diff --git a/products/warehouse_sources/backend/models/external_data_source.py b/products/warehouse_sources/backend/models/external_data_source.py
index 3455c6fe47fd..f3ecd3653b6c 100644
--- a/products/warehouse_sources/backend/models/external_data_source.py
+++ b/products/warehouse_sources/backend/models/external_data_source.py
@@ -5,7 +5,6 @@ from django.db import models, transaction
from django.utils import timezone
import structlog
-from prometheus_client import Counter
from posthog.exceptions_capture import capture_exception
from posthog.helpers.encrypted_fields import EncryptedJSONField
@@ -26,11 +25,6 @@ from products.warehouse_sources.backend.types import (
logger = structlog.get_logger(__name__)
-SOURCE_CREDENTIALS_RELEASE_FAILED_COUNTER = Counter(
- "warehouse_source_credentials_release_failed_total",
- "Credentials row releases that failed while soft deleting a warehouse source",
-)
-
MANAGED_WAREHOUSE_SOURCE_PREFIX = "managed_warehouse"
MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND = "project_reader"
MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND = "duckgres_service"
@@ -362,24 +356,6 @@ class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
else:
source.cleanup_cdc_resources_on_deletion(self)
source.on_source_deleted(self)
- self._release_credentials()
-
- def _release_credentials(self) -> None:
- # The credentials row is a separate store, so a failure here must not undo the soft delete.
- # The store never deletes the row: a row that nothing uses stays in the integrations list.
- from products.warehouse_sources.backend.logic.source_credentials import ( # noqa: PLC0415 — the store imports this model
- WarehouseSourceCredentialsStore,
- )
-
- if self.credentials_integration_id is None:
- return
- # The savepoint keeps a database error here from poisoning a caller's enclosing transaction.
- try:
- with transaction.atomic():
- WarehouseSourceCredentialsStore.release(self)
- except Exception as e:
- capture_exception(e, {"source_id": str(self.id), "team_id": self.team_id})
- SOURCE_CREDENTIALS_RELEASE_FAILED_COUNTER.inc()
def reload_schemas(self):
# temporalio at module scope would put the Temporal client on the django.setup() path —
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
index 1f42a08c5371..6e69d05d8c2a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
@@ -583,6 +583,14 @@ class _BaseSource(ABC, Generic[ConfigType]):
declared |= {config_field.name for config_field in dataclasses.fields(self._config_class)}
return frozenset(self.connection_host_fields) | (GENERIC_IDENTITY_FIELDS & declared)
+ @property
+ def integration_id_fields_point_at_integrations(self) -> bool:
+ """True when each ``*_integration_id`` field of the inputs holds the id of a core ``Integration`` row.
+
+ The reconcile command checks that each such id points at a row. Override it to False when the source
+ keeps its OAuth rows in another model."""
+ return True
+
@property
def credential_kind(self) -> str | None:
"""The ``Integration`` kind that holds this source's typed-in credentials, or None when the source has none.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py
index e4648f1e6f24..ebdf8c9727ab 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
@@ -899,6 +899,11 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
# Custom keeps its own `job_inputs`, and its OAuth rows are not `Integration` rows.
return None
+ @property
+ def integration_id_fields_point_at_integrations(self) -> bool:
+ # The OAuth2 row pointer of Custom is a `CustomOAuth2Integration` id.
+ return False
+
# Custom REST sources are capped per team to keep abuse of the arbitrary-URL fetcher bounded.
max_instances_per_team = MAX_CUSTOM_SOURCES_PER_TEAM
diff --git a/products/warehouse_sources/backend/tests/management/test_source_credentials_commands.py b/products/warehouse_sources/backend/tests/management/test_source_credentials_commands.py
new file mode 100644
index 000000000000..98ef87f5044b
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/management/test_source_credentials_commands.py
@@ -0,0 +1,475 @@
+from io import StringIO
+from typing import Any
+from uuid import uuid4
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.core.management import call_command
+from django.core.management.base import CommandError
+
+from cryptography.fernet import Fernet
+from parameterized import parameterized
+
+from posthog.integrations import IntegrationManager
+from posthog.models.team import Team
+
+from products.warehouse_sources.backend.logic import source_credentials_sync
+from products.warehouse_sources.backend.logic.source_credentials import WarehouseSourceCredentialsStore
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+POSTGRES_INPUTS: dict[str, Any] = {
+ "host": "db.example.com",
+ "port": "5432",
+ "user": "reader",
+ "password": "fake-password-value",
+ "database": "app",
+ "schema": "public",
+}
+POSTGRES_CONNECTION = {key: POSTGRES_INPUTS[key] for key in ("host", "port", "user", "password", "database")}
+COLUMN = "credentials_integration_id"
+
+
+class _CredentialsCommandTestCase(BaseTest):
+ def _source(
+ self,
+ job_inputs: Any = None,
+ *,
+ team: Team | None = None,
+ source_type: str = ExternalDataSourceType.POSTGRES,
+ deleted: bool = False,
+ column: str | None = None,
+ ) -> ExternalDataSource:
+ return ExternalDataSource.objects.create(
+ team=team or self.team,
+ source_id=str(uuid4()),
+ connection_id=str(uuid4()),
+ status="Completed",
+ source_type=source_type,
+ job_inputs=POSTGRES_INPUTS if job_inputs is None else job_inputs,
+ deleted=deleted,
+ credentials_integration_id=column,
+ )
+
+ def _reference(self, source: ExternalDataSource) -> str | None:
+ return ExternalDataSource.objects.get(pk=source.pk).credentials_integration_id
+
+ def _row_fields(self, source: ExternalDataSource) -> dict[str, Any] | None:
+ return WarehouseSourceCredentialsStore.get(ExternalDataSource.objects.get(pk=source.pk))
+
+ def _rows(self, team: Team | None = None) -> list[Any]:
+ return IntegrationManager.source("postgresql").credentials.list((team or self.team).pk)
+
+ def _row_for(self, source: ExternalDataSource, fields: dict[str, Any]) -> str:
+ return str(WarehouseSourceCredentialsStore.create(ExternalDataSource.objects.get(pk=source.pk), fields))
+
+ def _link(self, source: ExternalDataSource, reference: str) -> None:
+ ExternalDataSource.objects.filter(pk=source.pk).update(credentials_integration_id=reference)
+
+ def _run(self, command: str, *args: str) -> str:
+ out = StringIO()
+ call_command(command, *args, stdout=out)
+ return out.getvalue()
+
+
+class TestBackfillWarehouseSourceCredentials(_CredentialsCommandTestCase):
+ def test_dry_run_is_the_default_and_writes_nothing(self) -> None:
+ source = self._source()
+
+ output = self._run("backfill_warehouse_source_credentials")
+
+ assert "Dry run" in output
+ assert "created=1" in output
+ assert self._rows() == []
+ assert self._reference(source) is None
+
+ def test_execute_creates_one_row_per_source_and_never_prints_values(self) -> None:
+ first = self._source()
+ second = self._source()
+
+ output = self._run("backfill_warehouse_source_credentials", "--execute")
+
+ assert self._row_fields(first) == POSTGRES_CONNECTION
+ assert self._row_fields(second) == POSTGRES_CONNECTION
+ assert self._reference(first) != self._reference(second)
+ assert SourceInputsStore.load_stored(ExternalDataSource.objects.get(pk=first.pk)) == POSTGRES_INPUTS
+ assert "fake-password-value" not in output
+ assert "db.example.com" not in output
+
+ def test_second_run_is_unchanged_and_a_changed_source_updates_its_row(self) -> None:
+ source = self._source()
+ self._run("backfill_warehouse_source_credentials", "--execute")
+ reference = self._reference(source)
+
+ assert "unchanged=1" in self._run("backfill_warehouse_source_credentials", "--execute")
+
+ ExternalDataSource.objects.filter(pk=source.pk).update(
+ job_inputs={**POSTGRES_INPUTS, "password": "other-fake-password"}
+ )
+ output = self._run("backfill_warehouse_source_credentials", "--execute")
+
+ assert "updated=1" in output
+ assert self._reference(source) == reference
+ assert self._row_fields(source) == {**POSTGRES_CONNECTION, "password": "other-fake-password"}
+ assert len(self._rows()) == 1
+
+ @parameterized.expand(
+ [
+ (
+ "no_connection_fields",
+ ExternalDataSourceType.POSTGRES,
+ {"schema": "public"},
+ None,
+ "skipped_no_row",
+ None,
+ ),
+ ("oauth_only", ExternalDataSourceType.HUBSPOT, {"hubspot_integration_id": "7"}, None, "oauth_linked", "7"),
+ (
+ "oauth_short_key",
+ ExternalDataSourceType.SNAPCHATADS,
+ {"snapchat_integration_id": "7"},
+ None,
+ "oauth_linked",
+ "7",
+ ),
+ (
+ "oauth_option",
+ ExternalDataSourceType.STRIPE,
+ {"auth_method": {"selection": "oauth", "stripe_integration_id": "7"}},
+ None,
+ "oauth_linked",
+ "7",
+ ),
+ (
+ "bigquery_service_account",
+ ExternalDataSourceType.BIGQUERY,
+ {"auth_type": {"selection": "service_account", "google_cloud_service_account_integration_id": "7"}},
+ None,
+ "oauth_linked",
+ "7",
+ ),
+ (
+ "slack_hidden_key",
+ ExternalDataSourceType.SLACK,
+ {"slack_integration_id": "7"},
+ None,
+ "oauth_linked",
+ "7",
+ ),
+ (
+ "oauth_column_already_set",
+ ExternalDataSourceType.HUBSPOT,
+ {"hubspot_integration_id": "7"},
+ "7",
+ "unchanged",
+ "7",
+ ),
+ (
+ "oauth_column_differs",
+ ExternalDataSourceType.HUBSPOT,
+ {"hubspot_integration_id": "7"},
+ "8",
+ "oauth_linked",
+ "7",
+ ),
+ # The inputs hold no pointer, so they cannot tell the row. The column stays as it is.
+ ("oauth_without_pointer", ExternalDataSourceType.HUBSPOT, {}, "7", "skipped_no_row", "7"),
+ ]
+ )
+ def test_source_without_typed_in_credentials_gets_no_row(
+ self,
+ _name: str,
+ source_type: str,
+ job_inputs: dict[str, Any],
+ column: str | None,
+ outcome: str,
+ expected_column: str | None,
+ ) -> None:
+ source = self._source(job_inputs, source_type=source_type, column=column)
+
+ output = self._run("backfill_warehouse_source_credentials", "--execute")
+
+ assert f"{outcome}=1" in output
+ assert IntegrationManager.any.with_source_rows().list(self.team.pk) == []
+ assert self._reference(source) == expected_column
+ assert SourceInputsStore.load_stored(ExternalDataSource.objects.get(pk=source.pk)) == job_inputs
+
+ @parameterized.expand(
+ [
+ ("select_as_bare_string", {"auth_method": "oauth", "stripe_integration_id": "7"}),
+ ("flat_legacy_pointer", {"stripe_integration_id": "7"}),
+ ("unknown_selection", {"auth_method": {"selection": "legacy", "stripe_integration_id": "7"}}),
+ ]
+ )
+ def test_a_shape_the_walk_cannot_read_is_logged_and_skipped(self, _name: str, job_inputs: dict[str, Any]) -> None:
+ source = self._source(job_inputs, source_type=ExternalDataSourceType.STRIPE)
+
+ with patch.object(source_credentials_sync.logger, "warning") as warning:
+ output = self._run("backfill_warehouse_source_credentials", "--execute")
+
+ assert "skipped_unreadable_shape=1" in output
+ assert self._reference(source) is None
+ assert IntegrationManager.any.with_source_rows().list(self.team.pk) == []
+ warning.assert_called_once()
+
+ def test_a_stale_pointer_under_the_other_option_does_not_hide_typed_in_credentials(self) -> None:
+ source = self._source(
+ {"auth_method": {"selection": "api_key", "stripe_secret_key": "fake-key", "stripe_integration_id": "7"}},
+ source_type=ExternalDataSourceType.STRIPE,
+ )
+
+ output = self._run("backfill_warehouse_source_credentials", "--execute")
+
+ assert "created=1" in output
+ [row] = IntegrationManager.source("stripe").token.list(self.team.pk)
+ assert self._reference(source) == str(row.id)
+
+ @parameterized.expand(
+ [
+ ("other_team", ["other"], 0, 1),
+ ("this_team", ["this"], 1, 0),
+ ("both_teams", ["this", "other"], 1, 1),
+ ("no_match", ["none"], 0, 0),
+ ]
+ )
+ def test_team_filter(self, _name: str, teams: list[str], this_rows: int, other_rows: int) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ self._source()
+ self._source(team=other_team)
+ ids = {"this": self.team.id, "other": other_team.id, "none": 0}
+ args = [arg for team in teams for arg in ("--team-id", str(ids[team]))]
+
+ self._run("backfill_warehouse_source_credentials", "--execute", *args)
+
+ assert len(self._rows()) == this_rows
+ assert len(self._rows(other_team)) == other_rows
+
+ def test_source_type_filter(self) -> None:
+ postgres = self._source()
+ stripe = self._source(
+ {"auth_method": {"selection": "api_key", "stripe_secret_key": "fake-key"}},
+ source_type=ExternalDataSourceType.STRIPE,
+ )
+
+ self._run("backfill_warehouse_source_credentials", "--execute", "--source-type", "Postgres")
+
+ assert [row.id for row in self._rows()] == [int(self._reference(postgres) or 0)]
+ assert self._reference(stripe) is None
+
+ def test_unreadable_job_inputs_and_deleted_sources_are_skipped(self) -> None:
+ self._source("this is not json")
+ deleted = self._source(deleted=True)
+ good = self._source()
+
+ output = self._run("backfill_warehouse_source_credentials", "--execute")
+
+ assert "skipped_unreadable=1" in output
+ assert "created=1" in output
+ assert [row.id for row in self._rows()] == [int(self._reference(good) or 0)]
+ assert self._reference(deleted) is None
+
+ def test_a_rotation_after_the_batch_read_is_not_overwritten(self) -> None:
+ source = self._source()
+ rotated = {**POSTGRES_INPUTS, "password": "rotated-password"}
+ original = source_credentials_sync._sync_source
+
+ def rotate_then_sync(target: ExternalDataSource) -> str:
+ ExternalDataSource.objects.filter(pk=source.pk).update(job_inputs=rotated)
+ return original(target)
+
+ with patch.object(source_credentials_sync, "_sync_source", side_effect=rotate_then_sync):
+ self._run("backfill_warehouse_source_credentials", "--execute")
+
+ assert self._row_fields(source) == {**POSTGRES_CONNECTION, "password": "rotated-password"}
+
+ def test_a_reference_written_after_the_batch_read_gets_an_update_not_a_second_row(self) -> None:
+ source = self._source()
+ original = source_credentials_sync._sync_source
+
+ def link_then_sync(target: ExternalDataSource) -> str:
+ self._link(source, self._row_for(source, {**POSTGRES_CONNECTION, "password": "old"}))
+ return original(target)
+
+ with patch.object(source_credentials_sync, "_sync_source", side_effect=link_then_sync):
+ output = self._run("backfill_warehouse_source_credentials", "--execute")
+
+ assert "updated=1" in output
+ assert len(self._rows()) == 1
+ assert self._row_fields(source) == POSTGRES_CONNECTION
+
+ def test_an_undecryptable_leaf_is_skipped_and_keeps_the_existing_row(self) -> None:
+ foreign_ciphertext = Fernet(Fernet.generate_key()).encrypt(b"fake-password-value").decode()
+ source = self._source({**POSTGRES_INPUTS, "password": foreign_ciphertext})
+ self._link(source, self._row_for(source, POSTGRES_CONNECTION))
+
+ output = self._run("backfill_warehouse_source_credentials", "--execute")
+
+ assert "skipped_unreadable=1" in output
+ assert self._row_fields(source) == POSTGRES_CONNECTION
+
+ def test_a_dangling_reference_gets_a_new_row(self) -> None:
+ source = self._source(column="999999999")
+
+ output = self._run("backfill_warehouse_source_credentials", "--execute")
+
+ assert "recreated=1" in output
+ assert self._reference(source) != "999999999"
+ assert self._row_fields(source) == POSTGRES_CONNECTION
+
+ def test_a_shared_row_with_other_values_is_not_written(self) -> None:
+ owner = self._source()
+ pk = self._row_for(owner, POSTGRES_CONNECTION)
+ self._link(owner, pk)
+ other = self._source({**POSTGRES_INPUTS, "password": "other-fake-password"}, column=pk)
+
+ output = self._run("backfill_warehouse_source_credentials", "--execute")
+
+ assert "skipped_shared=1" in output
+ assert self._row_fields(other) == POSTGRES_CONNECTION
+
+ def test_batches_and_limit(self) -> None:
+ for _ in range(5):
+ self._source()
+
+ self._run("backfill_warehouse_source_credentials", "--execute", "--batch-size", "2", "--limit", "3")
+ assert len(self._rows()) == 3
+
+ self._run("backfill_warehouse_source_credentials", "--execute", "--batch-size", "2")
+ assert len(self._rows()) == 5
+
+ def test_invalid_batch_size_is_rejected(self) -> None:
+ with self.assertRaises(CommandError):
+ self._run("backfill_warehouse_source_credentials", "--batch-size", "0")
+
+
+class TestReconcileWarehouseSourceCredentials(_CredentialsCommandTestCase):
+ def test_reports_dangling_references_and_writes_nothing(self) -> None:
+ linked = self._source()
+ self._link(linked, self._row_for(linked, POSTGRES_CONNECTION))
+ hubspot_row = IntegrationManager.hubspot.oauth.create(self.team.pk, external_id="hub", config={})
+ self._source({"hubspot_integration_id": str(hubspot_row.id)}, source_type=ExternalDataSourceType.HUBSPOT)
+ typed_in_dangling = self._source(column="999999999")
+ oauth_dangling = self._source(
+ {"hubspot_integration_id": "999999998"}, source_type=ExternalDataSourceType.HUBSPOT
+ )
+ nested_dangling = self._source(
+ {"auth_method": {"selection": "oauth", "stripe_integration_id": "999999997"}},
+ source_type=ExternalDataSourceType.STRIPE,
+ )
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ other_team_row = IntegrationManager.hubspot.oauth.create(other_team.pk, external_id="hub", config={})
+ cross_team = self._source(
+ {"hubspot_integration_id": str(other_team_row.id)}, source_type=ExternalDataSourceType.HUBSPOT
+ )
+ self._source({"auth_oauth2_integration_id": "999999996"}, source_type=ExternalDataSourceType.CUSTOM)
+
+ output = self._run("reconcile_warehouse_source_credentials")
+
+ assert "references=6 dangling=4" in output
+ for source, key in [
+ (typed_in_dangling, COLUMN),
+ (oauth_dangling, "hubspot_integration_id"),
+ (nested_dangling, "stripe_integration_id"),
+ (cross_team, "hubspot_integration_id"),
+ ]:
+ assert f"source={source.id} type={source.source_type} key={key}" in output
+ assert "fake-password-value" not in output
+ assert self._reference(typed_in_dangling) == "999999999"
+ assert len(self._rows()) == 1
+
+ @parameterized.expand(
+ [
+ # (name, inputs pointer, column, mismatched, dangling)
+ ("column_differs_from_the_in_use_pointer", "first", "second", True, False),
+ ("column_matches", "first", "first", False, False),
+ ("column_names_no_row", "first", "999999999", True, True),
+ ("column_is_a_uuid", "first", "0b7e8c3a-5f4d-4e2a-9c1b-2d3e4f5a6b7c", True, True),
+ ("column_without_pointer_in_inputs", None, "999999999", False, True),
+ ]
+ )
+ def test_reports_an_oauth_column_that_differs_or_dangles(
+ self, _name: str, pointer: str | None, column: str, mismatched: bool, dangling: bool
+ ) -> None:
+ rows = {
+ name: str(IntegrationManager.hubspot.oauth.create(self.team.pk, external_id=name, config={}).id)
+ for name in ("first", "second")
+ }
+ source = self._source(
+ {} if pointer is None else {"hubspot_integration_id": rows[pointer]},
+ source_type=ExternalDataSourceType.HUBSPOT,
+ column=rows.get(column, column),
+ )
+
+ output = self._run("reconcile_warehouse_source_credentials")
+
+ assert (f"mismatched: team={self.team.pk} source={source.id}" in output) == mismatched
+ assert (f"dangling: team={self.team.pk} source={source.id} type=Hubspot key={COLUMN}" in output) == dangling
+ assert f"mismatched={int(mismatched)}" in output
+
+ def test_verify_fails_on_a_column_that_differs_from_the_in_use_pointer(self) -> None:
+ first, second = (
+ str(IntegrationManager.hubspot.oauth.create(self.team.pk, external_id=name, config={}).id)
+ for name in ("first", "second")
+ )
+ self._source({"hubspot_integration_id": first}, source_type=ExternalDataSourceType.HUBSPOT, column=second)
+
+ with self.assertRaises(CommandError) as raised:
+ self._run("reconcile_warehouse_source_credentials", "--verify")
+
+ assert "1 columns differ from the inputs" in str(raised.exception)
+
+ def test_verify_fails_on_a_source_of_unknown_type(self) -> None:
+ self._source(source_type="NotARealSource")
+
+ with self.assertRaises(CommandError):
+ self._run("reconcile_warehouse_source_credentials", "--verify")
+
+ def test_verify_reports_missing_and_mismatched_rows_and_fails(self) -> None:
+ self._source()
+ mismatched = self._source()
+ matching = self._source()
+ for source, fields in [
+ (mismatched, {**POSTGRES_CONNECTION, "password": "different"}),
+ (matching, POSTGRES_CONNECTION),
+ ]:
+ self._link(source, self._row_for(source, fields))
+
+ out = StringIO()
+ with self.assertRaises(CommandError) as raised:
+ call_command("reconcile_warehouse_source_credentials", "--verify", stdout=out)
+
+ assert "2 sources" in str(raised.exception)
+ assert "missing_reference=1" in out.getvalue()
+ assert "differs_or_unreadable_row=1" in out.getvalue()
+ assert "unchanged=1" in out.getvalue()
+ assert "different" not in out.getvalue()
+
+ def test_verify_fails_on_a_dangling_reference(self) -> None:
+ self._source({"hubspot_integration_id": "999999998"}, source_type=ExternalDataSourceType.HUBSPOT)
+
+ with self.assertRaises(CommandError) as raised:
+ self._run("reconcile_warehouse_source_credentials", "--verify")
+
+ assert "1 references point at no row" in str(raised.exception)
+
+ def test_verify_passes_when_every_source_has_a_matching_row(self) -> None:
+ self._source()
+ hubspot_row = IntegrationManager.hubspot.oauth.create(self.team.pk, external_id="hub", config={})
+ self._source({"hubspot_integration_id": str(hubspot_row.id)}, source_type=ExternalDataSourceType.HUBSPOT)
+ self._run("backfill_warehouse_source_credentials", "--execute")
+
+ assert "Verified" in self._run("reconcile_warehouse_source_credentials", "--verify")
+
+ def test_a_row_without_an_optional_key_matches_job_inputs_that_hold_it_as_none(self) -> None:
+ # A parsed config writes its unset optional fields as None, and the store does not rewrite the row for that.
+ source = self._source({**POSTGRES_INPUTS, "connection_string": None})
+ self._link(source, self._row_for(source, POSTGRES_CONNECTION))
+
+ assert "unchanged=1" in self._run("backfill_warehouse_source_credentials")
+ assert "Verified" in self._run("reconcile_warehouse_source_credentials", "--verify")
+
+ def test_invalid_batch_size_is_rejected(self) -> None:
+ with self.assertRaises(CommandError):
+ self._run("reconcile_warehouse_source_credentials", "--batch-size", "0")
diff --git a/products/warehouse_sources/backend/tests/test_source_credentials.py b/products/warehouse_sources/backend/tests/test_source_credentials.py
index c7b978266cf5..69c543f41e96 100644
--- a/products/warehouse_sources/backend/tests/test_source_credentials.py
+++ b/products/warehouse_sources/backend/tests/test_source_credentials.py
@@ -257,7 +257,6 @@ class TestWarehouseSourceCredentialsStore(BaseTest):
assert not Integration.objects._with_auth(AuthTypeSelector.ANY).filter(team_id=self.team.pk).exists()
source.credentials_integration_id = "1"
assert WarehouseSourceCredentialsStore.get(source) is None
- assert WarehouseSourceCredentialsStore.release(source) is False
@parameterized.expand(
[
@@ -293,7 +292,6 @@ class TestWarehouseSourceCredentialsStore(BaseTest):
assert WarehouseSourceCredentialsStore.get(source) is None
assert WarehouseSourceCredentialsStore.get_many([source]) == {}
- assert WarehouseSourceCredentialsStore.release(source) is False
with self.assertRaises(CredentialsNotFoundError):
WarehouseSourceCredentialsStore.update(source, {**PG_FIELDS, "password": "new"})
assert self._fields_of_row(store_pk) == PG_FIELDS
@@ -579,29 +577,17 @@ class TestWarehouseSourceCredentialsStore(BaseTest):
WarehouseSourceCredentialsStore.update(postgres, PG_FIELDS)
assert WarehouseSourceCredentialsStore.get(stripe) == STRIPE_FIELDS
- @parameterized.expand(
- [
- ("orphan", False, True),
- ("still_used_by_another_source", True, False),
- ]
- )
- def test_release_never_deletes_the_row(self, _name: str, shared: bool, orphaned: bool) -> None:
+ def test_soft_delete_keeps_the_row_and_looks_up_no_usages(self) -> None:
source = self._source()
- pk = self._create(source, PG_FIELDS)
- if shared:
- self._referencing(pk)
-
- assert WarehouseSourceCredentialsStore.release(source) is orphaned
- assert IntegrationManager.source("postgresql").credentials.get(self.team.id, pk).id == pk
+ self._create(source, PG_FIELDS)
- def test_release_of_a_reference_the_source_cannot_use_is_a_no_op(self) -> None:
- source = self._source()
- oauth_row = IntegrationManager.hubspot.oauth.create(self.team.id, external_id="H1", config={})
+ with patch("products.warehouse_sources.backend.integration_usages.list_sources_using_integration") as usages:
+ source.soft_delete()
- source.credentials_integration_id = str(oauth_row.id)
- assert WarehouseSourceCredentialsStore.release(source) is False
- source.credentials_integration_id = None
- assert WarehouseSourceCredentialsStore.release(source) is False
+ usages.assert_not_called()
+ source.refresh_from_db()
+ assert source.deleted is True
+ assert len(IntegrationManager.source("postgresql").any.list(self.team.id)) == 1
@parameterized.expand(
[
@@ -633,26 +619,6 @@ class TestWarehouseSourceCredentialsStore(BaseTest):
assert IntegrationManager.hubspot.oauth.get(self.team.id, oauth_row.id).id == oauth_row.id
- @patch("products.warehouse_sources.backend.models.external_data_source.capture_exception")
- def test_soft_delete_keeps_the_row_and_survives_store_failure(self, capture: Any) -> None:
- deleted, failing, without_row = self._source(), self._source(), self._source()
- for source in (deleted, failing):
- self._create(source, PG_FIELDS)
-
- with patch.object(
- WarehouseSourceCredentialsStore, "release", wraps=WarehouseSourceCredentialsStore.release
- ) as release:
- deleted.soft_delete()
- without_row.soft_delete()
- release.assert_called_once_with(deleted)
- assert len(IntegrationManager.source("postgresql").any.list(self.team.id)) == 2
-
- with patch.object(WarehouseSourceCredentialsStore, "release", side_effect=RuntimeError("boom")):
- failing.soft_delete()
- failing.refresh_from_db()
- assert failing.deleted is True
- capture.assert_called_once()
-
@parameterized.expand(
[
("top_level_int", {"linear_integration_id": 7}, True),