:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): store source credentials in provider-kind integration rows (#124087)
Tom Owers1823d01ea010
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.mdindex 826ce2ae0a2b..8c03053d29be 100644--- a/.agents/skills/implementing-warehouse-sources/SKILL.md+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md@@ -449,6 +449,20 @@ Read and write a source's `job_inputs` only through `SourceInputsStore` (`producThe semgrep rule `warehouse-source-inputs-go-through-store` blocks `source.job_inputs` and `job_inputs=` on `ExternalDataSource` outside the store. Tests and migrations can still set the field directly.+#### Connection fields in an Integration row++A source's typed-in connection fields go to one `Integration` row of the source's credential kind (see "Credential kind"). `WarehouseSourceCredentialsStore` (`products/warehouse_sources/backend/logic/source_credentials.py`) is the only code that reads or writes these rows. It goes through the integrations SDK: `IntegrationManager.source(kind).token` or `.credentials` (`posthog/integrations/manager.py`). It never uses the `Integration` model directly.++- The source points at its row with its `credentials_integration_id` column, not with a key in its inputs. The column holds the string form of `IntegrationReference` (`posthog/integrations/references.py`): a decimal legacy id, or later a UUID. Never parse or format it yourself.+- `WarehouseSourceCredentialsStore.create` and `update` set the column on the source and do not save it. Save the source with its inputs in the same write: `SourceInputsStore.save` and `create`, and a full model save, write the column. `SourceInputsStore.update_runtime` does not write it.+- An OAuth source keeps its own `*_integration_id` key and gets no new row. Account selectors stay in `job_inputs`, because several sources can share one OAuth row.+- 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.+- `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 (named "unreadable source: ..."), but not of a typed-in row, because the column always reads. The SDK reads it 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.+## Implementing `source_for_pipeline`Return a `SourceResponse` directly. **Do not** use `dlt_source_to_source_response` for new sources — DLT is being removed.diff --git a/frontend/src/lib/integrations/integrationsLogic.test.ts b/frontend/src/lib/integrations/integrationsLogic.test.tsindex bd55fe125b36..a7e810f1d833 100644--- a/frontend/src/lib/integrations/integrationsLogic.test.ts+++ b/frontend/src/lib/integrations/integrationsLogic.test.ts@@ -338,6 +338,18 @@ describe('integrationsLogic', () => {})})+ describe('warehouse source credentials rows', () => {+ it('keeps them in the full list but out of the lists that pick a connection by kind', async () => {+ const sourceRow = githubIntegration({ id: 43, config: { warehouse_source_type: 'Github' } })+ integrationsPayload = [githubIntegration(), sourceRow]+ await expectLogic(logic, () => logic.actions.loadIntegrations()).toFinishAllListeners()++ expect(logic.values.integrations?.map((integration) => integration.id)).toEqual([42, 43])+ expect(logic.values.githubIntegrations.map((integration) => integration.id)).toEqual([42])+ expect(logic.values.getIntegrationsByKind(['github']).map((integration) => integration.id)).toEqual([42])+ })+ })+describe('polling', () => {it('polls integrations only while at least one surface is subscribed', async () => {jest.useFakeTimers()diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.tsindex 7a3dc2f0de55..4c008ff8247a 100644--- a/frontend/src/lib/integrations/integrationsLogic.ts+++ b/frontend/src/lib/integrations/integrationsLogic.ts@@ -186,6 +186,7 @@ export interface integrationsLogicValues {newIntegrationModalId: string | nullnewIntegrationModalKind: IntegrationKind | nullpollingSubscribers: number+ providerIntegrations: IntegrationType[] | nullrequestedAccessKinds: IntegrationKind[]selectedIntegration: IntegrationType | nullsetupModalOpen: boolean@@ -697,9 +698,10 @@ export interface integrationsLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface integrationsLogicMeta {__keaTypeGenInternalSelectorTypes: {- slackIntegrations: (integrations: IntegrationType[] | null) => IntegrationType[] | undefined- githubIntegrations: (integrations: IntegrationType[] | null) => IntegrationType[]- linearIntegrations: (integrations: IntegrationType[] | null) => IntegrationType[]+ providerIntegrations: (integrations: IntegrationType[] | null) => IntegrationType[] | null+ slackIntegrations: (providerIntegrations: IntegrationType[] | null) => IntegrationType[] | undefined+ githubIntegrations: (providerIntegrations: IntegrationType[] | null) => IntegrationType[]+ linearIntegrations: (providerIntegrations: IntegrationType[] | null) => IntegrationType[]githubAvailableInstallations: (githubAvailableInstallationsResponse: GitHubAvailableInstallationsResponseApi | null,githubDiscoveryProjectId: number | string | null,@@ -709,7 +711,7 @@ export interface integrationsLogicMeta {githubAvailableInstallationsResponse: GitHubAvailableInstallationsResponseApi | null) => boolean | nullgetIntegrationsByKind: (- integrations: IntegrationType[] | null+ providerIntegrations: IntegrationType[] | null) => (kinds: (| 'apns'@@ -1444,22 +1446,30 @@ export const integrationsLogic = kea<integrationsLogicType>([},})),selectors({- slackIntegrations: [+ // The list also has the rows where data warehouse sources keep their typed-in credentials. Such a+ // row has a provider kind (`github`, `slack`), but it is not a connection of that provider. Code+ // that picks a connection by its kind reads this list.+ providerIntegrations: [(s) => [s.integrations],- (integrations: IntegrationType[] | null) => {- return integrations?.filter((x) => x.kind == 'slack')+ (integrations: IntegrationType[] | null): IntegrationType[] | null =>+ integrations?.filter((integration) => !integration.config?.warehouse_source_type) ?? null,+ ],+ slackIntegrations: [+ (s) => [s.providerIntegrations],+ (providerIntegrations: IntegrationType[] | null) => {+ return providerIntegrations?.filter((x) => x.kind == 'slack')},],githubIntegrations: [- (s) => [s.integrations],- (integrations: IntegrationType[] | null): IntegrationType[] => {- return integrations?.filter((x) => x.kind === 'github') ?? []+ (s) => [s.providerIntegrations],+ (providerIntegrations: IntegrationType[] | null): IntegrationType[] => {+ return providerIntegrations?.filter((x) => x.kind === 'github') ?? []},],linearIntegrations: [- (s) => [s.integrations],- (integrations: IntegrationType[] | null): IntegrationType[] => {- return integrations?.filter((x) => x.kind === 'linear') ?? []+ (s) => [s.providerIntegrations],+ (providerIntegrations: IntegrationType[] | null): IntegrationType[] => {+ return providerIntegrations?.filter((x) => x.kind === 'linear') ?? []},],githubAvailableInstallations: [@@ -1479,9 +1489,9 @@ export const integrationsLogic = kea<integrationsLogicType>([},],getIntegrationsByKind: [- (s) => [s.integrations],- (integrations: IntegrationType[] | null) => {- return (kinds: IntegrationKind[]) => integrations?.filter((i) => kinds.includes(i.kind)) || []+ (s) => [s.providerIntegrations],+ (providerIntegrations: IntegrationType[] | null) => {+ return (kinds: IntegrationKind[]) => providerIntegrations?.filter((i) => kinds.includes(i.kind)) || []},],diff --git a/frontend/src/lib/integrations/slackConnectLogic.ts b/frontend/src/lib/integrations/slackConnectLogic.tsindex 0347ebed5b04..7a5418f7b497 100644--- a/frontend/src/lib/integrations/slackConnectLogic.ts+++ b/frontend/src/lib/integrations/slackConnectLogic.ts@@ -111,11 +111,12 @@ export const slackConnectLogic: LogicWrapper<slackConnectLogicType> = kea<slackC{ pauseOnPageHidden: false })},- loadIntegrationsSuccess: ({ integrations }) => {+ loadIntegrationsSuccess: () => {if (!values.waitingForSlack) {return}- const slackIntegrations = integrations.filter((integration) => integration.kind === 'slack')+ // The reducer of integrationsLogic holds the loaded list by now.+ const slackIntegrations = values.slackIntegrations ?? []const known: Set<number> | null = cache.knownSlackIntegrationIdsif (!known) {cache.knownSlackIntegrationIds = new Set(slackIntegrations.map((integration) => integration.id))diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardCloudRunLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardCloudRunLogic.tsindex 68a06627689f..d996b48c484d 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardCloudRunLogic.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardCloudRunLogic.ts@@ -32,7 +32,7 @@ export const WIZARD_CLOUD_RUN_WORKFLOW_ID = 'posthog-integration'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface wizardCloudRunLogicValues {- integrations: IntegrationType[] | null // integrationsLogic+ githubIntegrations: IntegrationType[] // integrationsLogicinstallStepReturnUrl: string // onboardingLogicselectedSDK: SDK | null // sdksLogiccurrentProjectId: number | string // teamLogic@@ -92,7 +92,7 @@ export interface wizardCloudRunLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface wizardCloudRunLogicMeta {__keaTypeGenInternalSelectorTypes: {- githubIntegration: (integrations: IntegrationType[] | null) => IntegrationType | null+ githubIntegration: (githubIntegrations: IntegrationType[]) => IntegrationType | nullisGithubConnected: (githubIntegration: IntegrationType | null) => booleanconnectGitHubUrl: (currentProjectId: number | string, installStepReturnUrl: string) => stringskillId: (selectedSDK: SDK | null) => string | undefined@@ -123,7 +123,7 @@ export const wizardCloudRunLogic = kea<wizardCloudRunLogicType>([connect(() => ({values: [integrationsLogic,- ['integrations'],+ ['githubIntegrations'],teamLogic,['currentProjectId'],onboardingLogic,@@ -184,9 +184,8 @@ export const wizardCloudRunLogic = kea<wizardCloudRunLogicType>([}),selectors({githubIntegration: [- (s) => [s.integrations],- (integrations: IntegrationType[] | null): IntegrationType | null =>- integrations?.find((i) => i.kind === 'github') ?? null,+ (s) => [s.githubIntegrations],+ (githubIntegrations: IntegrationType[]): IntegrationType | null => githubIntegrations[0] ?? null,],isGithubConnected: [(s) => [s.githubIntegration],diff --git a/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts b/frontend/src/scenes/surveys/surveyNotificationModalLogic.tsindex a0e1baee38c4..d2b45b4b480b 100644--- a/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts+++ b/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts@@ -1001,7 +1001,7 @@ function getNotificationFormErrors(// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface surveyNotificationModalLogicValues {- integrations: IntegrationType[] | null // integrationsLogic+ providerIntegrations: IntegrationType[] | null // integrationsLogicsurvey: NewSurvey | Survey // surveyLogicsurveyLoading: boolean // surveyLogicsurveyNotifications: HogFunctionType[] // surveyLogic@@ -1261,9 +1261,9 @@ export interface surveyNotificationModalLogicActions {export interface surveyNotificationModalLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {- hasSlackIntegration: (integrations: IntegrationType[] | null) => boolean+ hasSlackIntegration: (providerIntegrations: IntegrationType[] | null) => booleanselectedSlackIntegration: (- integrations: IntegrationType[] | null,+ providerIntegrations: IntegrationType[] | null,notificationForm: SurveyNotificationForm) => IntegrationType | nulltemplateGlobals: (@@ -1294,7 +1294,7 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicTypeconnect((props: SurveyNotificationModalLogicProps) => ({values: [integrationsLogic,- ['integrations'],+ ['providerIntegrations'],surveyLogic({ id: props.surveyId }),['survey', 'surveyLoading', 'surveyNotifications', 'surveyNotificationsLoading'],teamLogic,@@ -1432,8 +1432,9 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicTypegetNotificationFormErrors(form,values.survey,- (values.integrations?.some((integration: IntegrationType) => integration.kind === 'slack') ??- false) as boolean+ (values.providerIntegrations?.some(+ (integration: IntegrationType) => integration.kind === 'slack'+ ) ?? false) as boolean),submit: async (form: SurveyNotificationForm) => {const payload = await buildSurveyNotificationPayload({@@ -1454,15 +1455,16 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicTypeselectors({hasSlackIntegration: [- (s) => [s.integrations],- (integrations: IntegrationType[] | null) =>- integrations?.some((integration: IntegrationType) => integration.kind === 'slack') ?? false,+ (s) => [s.providerIntegrations],+ (providerIntegrations: IntegrationType[] | null) =>+ providerIntegrations?.some((integration: IntegrationType) => integration.kind === 'slack') ?? false,],selectedSlackIntegration: [- (s) => [s.integrations, s.notificationForm],- (integrations: IntegrationType[] | null, form: SurveyNotificationForm) =>- integrations?.find((integration: IntegrationType) => integration.id === form.slackIntegrationId) ??- null,+ (s) => [s.providerIntegrations, s.notificationForm],+ (providerIntegrations: IntegrationType[] | null, form: SurveyNotificationForm) =>+ providerIntegrations?.find(+ (integration: IntegrationType) => integration.id === form.slackIntegrationId+ ) ?? null,],templateGlobals: [(s) => [s.survey, s.currentTeam],diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex fe8a1f95c6ed..20cb4d7173d7 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -2,8 +2,8 @@ import osimport reimport jsonimport time-from collections.abc import Callable, Iterable-from typing import Any, NoReturn, Protocol, cast+from collections.abc import Callable+from typing import Any, NoReturn, castfrom urllib.parse import urlencodefrom uuid import uuid4@@ -17,10 +17,17 @@ from django.utils import timezonefrom django.utils.dateparse import parse_datetimeimport structlog+from django_filters import rest_framework as filtersfrom django_filters.rest_framework import DjangoFilterBackendfrom django_redis.cache import RedisCachefrom django_redis.exceptions import ConnectionInterrupted-from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field, extend_schema_serializer+from drf_spectacular.utils import (+ OpenApiResponse,+ extend_schema,+ extend_schema_field,+ extend_schema_serializer,+ extend_schema_view,+)from prometheus_client import Counterfrom redis.exceptions import RedisErrorfrom rest_framework import mixins, serializers, status, viewsets@@ -72,7 +79,7 @@ from posthog.egress.limiter.policies import Priorityfrom posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.fuzzy_search import fuzzy_filter-from posthog.integrations import IntegrationNotFound, IntegrationRecord+from posthog.integrations import IntegrationManager, IntegrationNotFound, IntegrationRecord, IntegrationUsagefrom posthog.models import OrganizationMembership, Userfrom posthog.models.github_integration_base import GitHubIntegrationBasefrom posthog.models.integration import (@@ -88,6 +95,7 @@ from posthog.models.integration import (POSTHOG_CONNECT_GRANTABLE_SCOPES,POSTHOG_CONNECT_KIND,POSTHOG_SLACK_SCOPE,+ PUBLIC_INTEGRATION_KIND_CHOICES,SLACK_INTEGRATION_KINDS,AnthropicIntegration,ApplePushIntegration,@@ -130,7 +138,7 @@ from posthog.models.integration import (defer_repository_cache_fields,resolve_aliased_oauth_kind,)-from posthog.models.integration.auth_types import rows_without_source_marker_q+from posthog.models.integration.auth_types import default_auth_type, rows_without_source_marker_qfrom posthog.models.integration.github_audit import GitHubAuditfrom posthog.models.integration.stripe import stripe_signing_secretfrom posthog.models.integration.twitter_ads import TwitterAdsIntegration@@ -149,12 +157,10 @@ from posthog.tasks.email import send_integration_access_requestfrom posthog.utils import absolute_uri, is_relative_urlfrom products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin-from products.batch_exports.backend.facade.api import list_batch_exports_using_integration-from products.cdp.backend.services.integration_usage import get_enabled_hog_functions_using_integrationfrom products.slack_app.backend.services.slack_auth import SLACK_AUTH_FAILURE_CODESfrom products.tasks.backend.facade.api import get_in_progress_runs_for_github_integrationfrom products.tasks.backend.facade.contracts import InProgressGithubRunsDTO-from products.workflows.backend.facade.api import get_active_workflows_using_integration, lookup_existing_email_tools+from products.workflows.backend.facade.api import lookup_existing_email_toolsfrom products.workflows.backend.facade.contracts import EmailProviderUnavailableErrorfrom products.workflows.backend.facade.enums import EmailDomainSetupMethod@@ -307,16 +313,33 @@ def _ensure_oauth_token_valid(instance: Integration) -> None:)-class _HasNameOrId(Protocol):- @property- def id(self) -> Any: ...-- @property- def name(self) -> str | None: ...---def _concat_names_or_ids(items: Iterable[_HasNameOrId]) -> str:- return ", ".join(sorted(it.name or str(it.id) for it in items))+# Keyed by the `IntegrationUsage.type` that each product's `integration_usages.py` reports. The order+# is the order of the message.+_USAGE_TYPE_LABELS: dict[str, str] = {+ "warehouse_source": "data warehouse sources",+ "workflow": "active workflows",+ "hog_function": "enabled data pipelines",+ "batch_export": "batch exports",+}+++def _integration_in_use_error(usages: list[IntegrationUsage]) -> ValidationError:+ # Integration management does not grant read access to the sources that block deletion.+ types = [*_USAGE_TYPE_LABELS, *sorted({usage.type for usage in usages} - set(_USAGE_TYPE_LABELS))]+ used_by = [+ f"{_USAGE_TYPE_LABELS.get(usage_type, usage_type)}: "+ + (+ str(sum(usage.type == usage_type for usage in usages))+ if usage_type == "warehouse_source"+ else ", ".join(sorted(usage.name for usage in usages if usage.type == usage_type))+ )+ for usage_type in types+ if any(usage.type == usage_type for usage in usages)+ ]+ return ValidationError(+ f"This integration is used by {' and '.join(used_by)}. "+ "Update them to use a different integration before disconnecting it."+ )def _github_disconnect_blocked_message(live_runs: InProgressGithubRunsDTO, team_id: int) -> str:@@ -765,7 +788,7 @@ class SlackUsersResponseSerializer(PageLinksSerializer):class IntegrationAccessRequestSerializer(serializers.Serializer):kind = serializers.ChoiceField(- choices=Integration.IntegrationKind.choices,+ choices=PUBLIC_INTEGRATION_KIND_CHOICES,help_text="The kind of integration the member is requesting be connected (e.g. 'slack', 'github').",)reason = serializers.CharField(@@ -786,6 +809,18 @@ class IntegrationAccessRequestResponseSerializer(serializers.Serializer):class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):"""Standard Integration serializer."""+ # A string, not an enum: a list can hold rows of kinds that a product registers, such as the kind of a+ # warehouse source's typed-in credentials. `validate_kind` limits a create to the public kinds.+ # Typed as a plain field, because the create request schema below swaps in a choice field.+ kind: serializers.Field = serializers.CharField(+ max_length=32,+ trim_whitespace=False,+ help_text=(+ "The provider of the integration, for example 'slack' or 'github'. A create accepts only the kinds "+ "that PostHog connects here. Data warehouse sources also store their typed-in credentials as "+ "integrations, under a kind per source type."+ ),+ )created_by = UserBasicSerializer(read_only=True)auth_type = serializers.ChoiceField(choices=IntegrationAuthType.choices,@@ -873,6 +908,8 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerialdef validate_kind(self, value: str) -> str:if value == Integration.IntegrationKind.SLACK_POSTHOG_CODE.value:raise ValidationError("This integration kind is deprecated and can no longer be created.")+ if value not in Integration.IntegrationKind.values:+ raise ValidationError(f'"{value}" is not a kind that can be connected here.')return valuedef create(self, validated_data: Any) -> Any:@@ -1383,6 +1420,16 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerialraise ValidationError("Kind not supported")+@extend_schema_serializer(component_name="IntegrationConfigCreate")+class IntegrationCreateRequestSerializer(IntegrationSerializer):+ """The request schema of a create. A create accepts only the public kinds, so the schema lists them."""++ kind = serializers.ChoiceField(+ choices=PUBLIC_INTEGRATION_KIND_CHOICES,+ help_text="The provider of the integration, for example 'slack' or 'github'.",+ )++class GitHubPrepareCallbackRequestSerializer(serializers.Serializer):next = serializers.CharField(required=False,@@ -1539,7 +1586,19 @@ class PersonalConnectionRecentAuthPermission(BasePermission):return True+class IntegrationFilterSet(filters.FilterSet):+ kind = filters.ChoiceFilter(choices=PUBLIC_INTEGRATION_KIND_CHOICES)++ class Meta:+ model = Integration+ fields = ["kind"]++@extend_schema(extensions={"x-product": "integrations"})+@extend_schema_view(+ # The response holds a string kind, because a list can hold kinds that a product registers.+ create=extend_schema(request=IntegrationCreateRequestSerializer, responses={201: IntegrationSerializer}),+)class IntegrationViewSet(TeamAndOrgViewSetMixin,mixins.CreateModelMixin,@@ -1594,7 +1653,7 @@ class IntegrationViewSet(queryset = defer_repository_cache_fields(Integration.objects._with_auth(ANY)).order_by("created_at", "id")serializer_class = IntegrationSerializerfilter_backends = [DjangoFilterBackend]- filterset_fields = ["kind"]+ filterset_class = IntegrationFilterSetdef safely_get_queryset(self, queryset: QuerySet) -> QuerySet:# A `posthog` connection holds the creator's delegated grant into another project plus personal@@ -1603,10 +1662,11 @@ class IntegrationViewSet(# list/retrieve — scope `posthog` rows to the requesting user. Other kinds stay team-visible.user_id = getattr(self.request.user, "id", None)queryset = queryset.exclude(Q(kind=POSTHOG_CONNECT_KIND) & ~Q(created_by_id=user_id))- # The other actions (destroy, channels, github_repos, ...) call provider code that reads the- # row in the default shape of its kind, so they keep to rows with the default auth type, and- # skip warehouse source rows, the same as the implicit filter of `Integration.objects`.- if self.action not in ("list", "retrieve"):+ # The other actions (channels, github_repos, ...) call provider code that reads the row in the+ # default shape of its kind, so they keep to rows with the default auth type, and skip warehouse+ # source rows, the same as the implicit filter of `Integration.objects`. Destroy accepts every+ # row, because the list shows every row, and skips provider teardown for the rest.+ if self.action not in ("list", "retrieve", "destroy"):assert isinstance(queryset, IntegrationQuerySet)queryset = queryset._with_auth(DEFAULT).filter(rows_without_source_marker_q())return queryset@@ -1642,35 +1702,15 @@ class IntegrationViewSet(return super().get_throttles()def perform_destroy(self, instance: Integration) -> None:- flows_using_integration = get_active_workflows_using_integration(- team_id=instance.team_id, integration_id=instance.id- )- functions_using_integration = get_enabled_hog_functions_using_integration(- team_id=instance.team_id, integration_id=instance.id- )- batch_exports_using_integration = list_batch_exports_using_integration(- team_id=instance.team_id, integration_id=instance.id- )-- used_by = []-- if flows_using_integration:- flow_names = _concat_names_or_ids(flows_using_integration)- used_by.append(f"active workflows: {flow_names}")-- if functions_using_integration:- function_names = _concat_names_or_ids(functions_using_integration)- used_by.append(f"enabled data pipelines: {function_names}")-- if batch_exports_using_integration:- batch_export_names = _concat_names_or_ids(batch_exports_using_integration)- used_by.append(f"batch exports: {batch_export_names}")-- if used_by:- raise ValidationError(- f"This integration is used by {' and '.join(used_by)}. "- "Update them to use a different integration before disconnecting it."- )+ # Check before the teardown below, which revokes grants at the provider. The delete at the end+ # does not check again, because a check decrypts the inputs of every warehouse source of the team.+ try:+ usages = IntegrationManager.any.with_source_rows().usages(instance.team_id, instance.id)+ except IntegrationNotFound:+ # A concurrent request (a second click, another tab) deleted the row after `get_object`.+ return+ if usages:+ raise _integration_in_use_error(usages)if instance.kind == "github":live_runs = get_in_progress_runs_for_github_integration(@@ -1679,13 +1719,17 @@ class IntegrationViewSet(if live_runs.count:raise ValidationError(_github_disconnect_blocked_message(live_runs, team_id=instance.team_id))- if instance.kind == "stripe":+ # Provider teardown (secret clearing, grant revoke, App uninstall) applies only to the connection+ # that the kind's default auth type describes. A typed-in key or token has no grant to revoke.+ provider_connection = instance.auth_type == default_auth_type(instance.kind).value++ if instance.kind == "stripe" and provider_connection:try:stripe_integration = StripeIntegration(instance)stripe_integration.clear_posthog_secrets()except Exception as e:capture_exception(e)- if instance.kind in OauthIntegration.supported_kinds:+ if instance.kind in OauthIntegration.supported_kinds and provider_connection:# Disconnecting should sever the grant at the provider too, not just delete our copy# of the tokens — otherwise the provider keeps treating the app as authorized.try:@@ -1695,9 +1739,11 @@ class IntegrationViewSet(except Exception as e:capture_exception(e)github_audit = (- GitHubAudit.project(instance, cast(User, self.request.user)) if instance.kind == "github" else None+ GitHubAudit.project(instance, cast(User, self.request.user))+ if instance.kind == "github" and provider_connection+ else None)- if instance.kind == "github" and instance.integration_id:+ if github_audit is not None and instance.integration_id:# Team integrations own the installation; personal ones are subordinate. When the# last team integration for an installation is removed, tear it down everywhere:# uninstall the App on GitHub and delete the now-orphaned personal integrations.@@ -1707,7 +1753,6 @@ class IntegrationViewSet(.exclude(id=instance.id).exists())- assert github_audit is not Nonegithub_audit.record("disconnect_started", last_reference=is_last_team_reference)if not is_last_team_reference:github_audit.record("uninstall_completed", outcome="skipped", reason="other_project_references")@@ -1736,7 +1781,9 @@ class IntegrationViewSet(github_audit.record("personal_cleanup_failed", failure_type=type(e).__name__)try:- super().perform_destroy(instance)+ IntegrationManager.any.with_source_rows().delete(instance.team_id, instance.id, ignore_usages=True)+ except IntegrationNotFound:+ pass # A concurrent request deleted the row during the teardown.except Exception as exc:if github_audit:github_audit.record("disconnect_failed", stage="project_deletion", failure_type=type(exc).__name__)diff --git a/posthog/api/test/__snapshots__/test_element.ambr b/posthog/api/test/__snapshots__/test_element.ambrindex 629717e7aac5..3692a2e12d7b 100644--- a/posthog/api/test/__snapshots__/test_element.ambr+++ b/posthog/api/test/__snapshots__/test_element.ambr@@ -569,6 +569,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex 349d6d3c7e76..aef9fd25770f 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -54,15 +54,19 @@ from posthog.credentials_service.errors import ()from posthog.egress.github.transport import GitHubEgressBudgetExhaustedfrom posthog.egress.limiter.policies import Priority+from posthog.integrations import IntegrationManager, IntegrationNotFound, IntegrationReader, IntegrationRecordfrom posthog.models.activity_logging.activity_log import ActivityLog, apply_activity_visibility_restrictionsfrom posthog.models.integration import (+ ANY as ANY_AUTH_TYPE,ERROR_TOKEN_REFRESH_FAILED,GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS,PRIVATE_CHANNEL_WITHOUT_ACCESS,SLACK_INTEGRATION_KINDS,STRIPE_POSTHOG_SECRET_NAMES,+ WAREHOUSE_SOURCE_TYPE_CONFIG_KEY,Assignee,AssigneeLookupFailed,+ AuthTypeSelector,EmailIntegration,GitHubInstallationAccess,GitHubIntegration,@@ -98,6 +102,8 @@ from products.batch_exports.backend.facade.enums import BatchExportDestinationTyfrom products.cdp.backend.models import HogFunctionfrom products.cdp.backend.models.hog_function_template import HogFunctionTemplatefrom products.tasks.backend.facade.contracts import InProgressGithubRunsDTO+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.workflows.backend.facade.contracts import EmailDomainVerification, WorkflowSummaryfrom products.workflows.backend.facade.testing import create_workflow_for_test@@ -3310,10 +3316,10 @@ class TestIntegrationAPIKeyAccess:assert repos.status_code == status.HTTP_404_NOT_FOUND# Only the App row of the list heals its account name. The token row has no installation.assert heal.call_count == 1- # Actions other than list and retrieve do not reach the warehouse source row.- deleted = client.delete(f"{base_url}/{source_row.id}/")- assert deleted.status_code == status.HTTP_404_NOT_FOUND- assert Integration._base_manager.filter(id=source_row.id).exists()+ # Actions other than list, retrieve and destroy do not reach the warehouse source row.+ # `test_destroy_of_a_source_credentials_row` covers destroy.+ source_repos = client.get(f"{base_url}/{source_row.id}/github_repos/")+ assert source_repos.status_code == status.HTTP_404_NOT_FOUNDdef test_list_integrations_filtered_by_kind(self, client: HttpClient):client.force_login(self.user)@@ -5425,6 +5431,29 @@ class TestStripeIntegration:assert response.status_code == status.HTTP_204_NO_CONTENTassert not Integration.objects.filter(id=integration.id).exists()+ @patch("posthog.api.integration.OauthIntegration")+ @patch("posthog.api.integration.StripeIntegration")+ def test_destroy_typed_in_row_skips_provider_teardown(+ self, MockStripeIntegration, MockOauthIntegration, client: HttpClient+ ):+ integration = Integration.objects._with_auth(ANY_AUTH_TYPE).create(+ team=self.team,+ kind="stripe",+ integration_id="typed-in",+ config={"auth_type": "token"},+ sensitive_config={"api_key": "sk_test_not_a_real_key"},+ created_by=self.user,+ )+ MockOauthIntegration.supported_kinds = ["stripe"]++ client.force_login(self.user)+ response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")++ assert response.status_code == status.HTTP_204_NO_CONTENT+ MockStripeIntegration.assert_not_called()+ MockOauthIntegration.assert_not_called()+ assert not Integration.objects._with_auth(ANY_AUTH_TYPE).filter(id=integration.id).exists()+def test_destroy_non_stripe_does_not_call_clear_secrets(self, client: HttpClient):integration = Integration.objects.create(team=self.team,@@ -7030,6 +7059,13 @@ class TestSlackPostHogCodeKindDeprecated:serializer.is_valid()assert "kind" not in serializer.errors+ def test_validate_kind_rejects_whitespace_padded_kind(self):+ # PersonalConnectionRecentAuthPermission compares the raw kind, so a trimmed kind would bypass it.+ serializer = IntegrationSerializer(data={"kind": "posthog ", "config": {}})++ assert not serializer.is_valid()+ assert "kind" in serializer.errors+class TestGitHubIntegrationListStatusFields:@pytest.fixture(autouse=True)@@ -8213,3 +8249,151 @@ class TestGitHubDiscoveryAudit(APIBaseTest):response = self.client.post(f"/api/projects/{self.team.id}/integrations/github/link_existing/", payload)assert response.status_code == 200assert link.call_args.kwargs["installation_id_param"] is None+++class TestWarehouseSourceIntegrationKind(APIBaseTest):+ def _credentials_row(self, kind: str, auth_type: str = "credentials") -> IntegrationRecord:+ rows = IntegrationManager.source(kind)+ return (rows.token if auth_type == "token" else rows.credentials).create(+ self.team.id,+ external_id=str(uuid4()),+ config={WAREHOUSE_SOURCE_TYPE_CONFIG_KEY: "Postgres", "display_name": "Postgres (prod)"},+ sensitive_config={"fields": {"password": "fake-password"}},+ )++ def _source_pointing_at(+ self, integration: IntegrationRecord, team=None, deleted: bool = False, by_column: bool = False+ ) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team=team or self.team,+ source_id=str(uuid4()),+ connection_id=str(uuid4()),+ status="Completed",+ source_type=ExternalDataSourceType.POSTGRES if by_column else ExternalDataSourceType.LINEAR,+ job_inputs={} if by_column else {"linear_integration_id": integration.id},+ credentials_integration_id=str(integration.id) if by_column else None,+ deleted=deleted,+ )++ @patch("posthog.api.integration.AnthropicIntegration")+ def test_detail_actions_do_not_reach_a_source_row_of_a_default_auth_type(self, anthropic: MagicMock) -> None:+ # `token` is the default auth type of `anthropic`, so only the source marker keeps the row out.+ row = self._credentials_row("anthropic", "token")++ response = self.client.get(f"/api/environments/{self.team.pk}/integrations/{row.id}/anthropic_managed_agents/")++ assert response.status_code == 404+ anthropic.assert_not_called()++ def test_typed_in_rows_are_listed_with_their_kind_and_auth_type(self) -> None:+ postgres = self._credentials_row("postgresql")+ stripe = self._credentials_row("stripe", "token")+ generated = self._credentials_row("ably", "token")++ listed = self.client.get(f"/api/projects/{self.team.id}/integrations/").json()["results"]++ by_id = {row["id"]: row for row in listed}+ assert {key: by_id[postgres.id][key] for key in ("kind", "auth_type", "display_name")} == {+ "kind": "postgresql",+ "auth_type": "credentials",+ "display_name": "Postgres (prod)",+ }+ assert (by_id[stripe.id]["kind"], by_id[stripe.id]["auth_type"]) == ("stripe", "token")+ assert (by_id[generated.id]["kind"], by_id[generated.id]["auth_type"]) == ("ably", "token")+ assert "fake-password" not in json.dumps(listed)+ assert self.client.get(f"/api/projects/{self.team.id}/integrations/{stripe.id}/").status_code == 200++ @parameterized.expand([("generated_kind", "ably"), ("unknown_kind", "not-a-kind")])+ def test_a_kind_outside_the_public_enum_cannot_be_created_or_filtered(self, _name: str, kind: str) -> None:+ response = self.client.post(+ f"/api/projects/{self.team.id}/integrations/", {"kind": kind, "config": {}}, format="json"+ )++ assert response.status_code == 400+ assert not Integration.objects._with_auth(AuthTypeSelector.ANY).filter(kind=kind).exists()+ assert self.client.get(f"/api/projects/{self.team.id}/integrations/?kind={kind}").status_code == 400++ @parameterized.expand(+ [+ ("referenced", "postgresql", "credentials", True, 400),+ ("unreferenced", "postgresql", "credentials", False, 204),+ # A typed-in row of an OAuth kind is deleted without the provider teardown.+ ("non_default_auth_type", "stripe", "token", False, 204),+ ]+ )+ def test_destroy_of_a_source_credentials_row(+ self, _name: str, kind: str, auth_type: str, referenced: bool, expected_status: int+ ) -> None:+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ row = self._credentials_row(kind, auth_type)+ if referenced:+ source = self._source_pointing_at(row, by_column=True)+ source.prefix = "private_source_prefix"+ source.save(update_fields=["prefix"])++ response = self.client.delete(f"/api/projects/{self.team.id}/integrations/{row.id}/")++ assert response.status_code == expected_status+ assert IntegrationManager.any.with_source_rows().exists(self.team.id, external_id=row.integration_id) == (+ expected_status != 204+ )+ if referenced:+ detail = json.dumps(response.json())+ assert "data warehouse sources: 1" in detail+ assert "private_source_prefix" not in detail+ assert str(source.source_type) not in detail+ assert str(source.id) not in detail++ @parameterized.expand([("before_the_usage_check", "usages"), ("during_the_teardown", "delete")])+ def test_destroy_of_a_row_that_a_concurrent_request_deleted(self, _name: str, gone_at: str) -> None:+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ row = self._credentials_row("postgresql")++ with (+ patch.object(IntegrationReader, "usages", return_value=[]),+ patch.object(IntegrationReader, gone_at, side_effect=IntegrationNotFound()),+ ):+ response = self.client.delete(f"/api/projects/{self.team.id}/integrations/{row.id}/")++ assert response.status_code == 204++ def test_destroy_checks_the_usages_once(self) -> None:+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ row = self._credentials_row("postgresql")++ with patch("posthog.integrations.accessors.integration_usages", return_value=[]) as usages:+ response = self.client.delete(f"/api/projects/{self.team.id}/integrations/{row.id}/")++ assert response.status_code == 204+ assert usages.call_count == 1+ assert not IntegrationManager.any.with_source_rows().exists(self.team.id, external_id=row.integration_id)++ @parameterized.expand(+ [+ ("referenced", False, False, 400),+ ("referenced_by_deleted_source", True, False, 204),+ ("referenced_by_other_team", False, True, 204),+ ("unreferenced", None, False, 204),+ ]+ )+ def test_destroy_is_blocked_by_a_source_pointer(+ self, _name: str, source_deleted: bool | None, other_team: bool, expected_status: int+ ) -> None:+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ integration = Integration.objects.create(team=self.team, kind="linear", integration_id="L1")+ if source_deleted is not None:+ source_team = Team.objects.create(organization=self.organization, name="Other") if other_team else self.team+ self._source_pointing_at(integration, team=source_team, deleted=source_deleted)++ with patch("posthog.api.integration.OauthIntegration") as oauth:+ oauth.supported_kinds = []+ response = self.client.delete(f"/api/projects/{self.team.id}/integrations/{integration.id}/")++ assert response.status_code == expected_status+ assert IntegrationManager.any.exists(self.team.id, external_id="L1") == (expected_status == 400)+ if expected_status == 400:+ assert "data warehouse sources" in json.dumps(response.json())diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambrindex ceadba403c64..27301e946364 100644--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr@@ -68,6 +68,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -261,6 +262,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",diff --git a/posthog/integrations/README.md b/posthog/integrations/README.mdindex b655c64cf0a3..6b1ea67ca6ca 100644--- a/posthog/integrations/README.md+++ b/posthog/integrations/README.md@@ -22,6 +22,7 @@ The rules for callers are in `AGENTS.md`.| `source_kinds.py` | The registry of warehouse source kinds || `usages.py` | The registry of usage providers || `fields.py` | `IntegrationReferenceField` for DRF serializers |+| `references.py` | `IntegrationReference`, the stored string form of a row reference |The model module imports `catalogue.py`, `contracts.py` and `enums.py`. These modules must not import the model.`__init__.py` loads `IntegrationManager` on first use for the same reason.@@ -173,6 +174,7 @@ def integration_usages(team_id: int, integration_id: int) -> list[IntegrationUsa```The SDK finds the module on the first call to `usages` or `delete`. Code outside a product calls `register_usage_provider` instead.+The product sets `IntegrationUsage.type` (for example `warehouse_source`, `workflow`, `hog_function`, `batch_export`). The integrations API names these types in its error when a delete finds usages.## Reference a row from a serializer@@ -183,6 +185,14 @@ With `kinds`, the field accepts only the default auth type of each kind, becausePass `auth_types=[AuthType.TOKEN]` to accept other auth types, or `auth_types="any"` to accept every auth type.The field never accepts a warehouse source row.+## Store a reference outside a serializer++A model that points at a row without a foreign key stores the reference as a string, for example `ExternalDataSource.credentials_integration_id`.+Rows in the credentials service get a UUID id, and keep the int id of a row made before as `legacy_id`.+So the string is a decimal legacy id (`"123"`) or a lowercase hyphenated UUID.+Write it with `str(IntegrationReference.from_legacy_id(row.id))`, and read it with `IntegrationReference.parse(value)`, which raises `ValueError` for any other form.+The accessors take int ids, so pass `reference.legacy_id`. A UUID reference cannot resolve yet: treat it as "not found".+## Why direct model use fails CIThe semgrep rule `.semgrep/rules/devex/integration-model-through-sdk.yaml` finds uses of the model outside the SDK: imports of `Integration`, its managers (`objects`, `_default_manager`, `_base_manager`, also through `IntegrationRecord`), `apps.get_model` lookups of it, relation fields to it, `select_related` and `prefetch_related` on an integration relation, `integration__` lookups (as keyword arguments or as strings), `integration_set`, and `.save()` on a row.diff --git a/posthog/integrations/__init__.py b/posthog/integrations/__init__.pyindex a2d7fc1c878f..2476502e9bb4 100644--- a/posthog/integrations/__init__.py+++ b/posthog/integrations/__init__.py@@ -22,6 +22,7 @@ from posthog.integrations.contracts import (UnsupportedIntegrationFilter,)from posthog.integrations.enums import AuthType, IntegrationAuthType+from posthog.integrations.references import IntegrationReferenceif TYPE_CHECKING:from posthog.integrations.kinds_generated import IntegrationKind@@ -79,6 +80,7 @@ __all__ = ["IntegrationPatch","IntegrationReader","IntegrationRecord",+ "IntegrationReference","IntegrationUsage","KindSpec","OAuthAccessor",diff --git a/posthog/integrations/catalogue.py b/posthog/integrations/catalogue.pyindex c2252bc0777d..92d243ee57f3 100644--- a/posthog/integrations/catalogue.py+++ b/posthog/integrations/catalogue.py@@ -28,7 +28,7 @@ KINDS: Mapping[str, KindSpec] = {"aws-s3": KindSpec(label="Amazon S3", default=_CREDENTIALS),"azure-blob": KindSpec(label="Azure Blob Storage", default=_CREDENTIALS),"bing-ads": KindSpec(label="Bing Ads", default=_OAUTH),- "clickup": KindSpec(label="ClickUp", default=_OAUTH, others=frozenset({_TOKEN})),+ "clickup": KindSpec(label="ClickUp", default=_OAUTH, others=frozenset({_TOKEN, _CREDENTIALS})),"customerio-app": KindSpec(label="Customer.io App API", default=_TOKEN),"customerio-track": KindSpec(label="Customer.io Track API", default=_TOKEN),"customerio-webhook": KindSpec(label="Customer.io webhook", default=_TOKEN),@@ -36,10 +36,10 @@ KINDS: Mapping[str, KindSpec] = {"email": KindSpec(label="Email", default=_CREDENTIALS),"firebase": KindSpec(label="Firebase", default=_CREDENTIALS),"github": KindSpec(label="GitHub", default=_OAUTH, others=frozenset({_TOKEN})),- "gitlab": KindSpec(label="GitLab", default=_TOKEN),+ "gitlab": KindSpec(label="GitLab", default=_TOKEN, others=frozenset({_CREDENTIALS})),"google-ads": KindSpec(label="Google Ads", default=_OAUTH),"google-analytics": KindSpec(label="Google Analytics", default=_OAUTH),- "google-calendar": KindSpec(label="Google Calendar", default=_OAUTH),+ "google-calendar": KindSpec(label="Google Calendar", default=_OAUTH, others=frozenset({_CREDENTIALS})),"google-cloud-service-account": KindSpec(label="Google Cloud service account", default=_CREDENTIALS),"google-cloud-storage": KindSpec(label="Google Cloud Storage", default=_CREDENTIALS),"google-pubsub": KindSpec(label="Google Pub/Sub", default=_CREDENTIALS),@@ -49,11 +49,11 @@ KINDS: Mapping[str, KindSpec] = {"hubspot": KindSpec(label="HubSpot", default=_OAUTH),"instagram": KindSpec(label="Instagram", default=_OAUTH),"intercom": KindSpec(label="Intercom", default=_OAUTH),- "jira": KindSpec(label="Jira", default=_OAUTH, others=frozenset({_TOKEN})),+ "jira": KindSpec(label="Jira", default=_OAUTH, others=frozenset({_TOKEN, _CREDENTIALS})),"linear": KindSpec(label="Linear", default=_OAUTH),"linkedin-ads": KindSpec(label="LinkedIn Ads", default=_OAUTH),"meta-ads": KindSpec(label="Meta Ads", default=_OAUTH),- "pardot": KindSpec(label="Pardot", default=_OAUTH),+ "pardot": KindSpec(label="Pardot", default=_OAUTH, others=frozenset({_CREDENTIALS})),"pinterest-ads": KindSpec(label="Pinterest Ads", default=_OAUTH),"postgresql": KindSpec(label="PostgreSQL", default=_CREDENTIALS),"posthog": KindSpec(label="PostHog", default=_OAUTH),@@ -67,8 +67,8 @@ KINDS: Mapping[str, KindSpec] = {"snowflake": KindSpec(label="Snowflake", default=_CREDENTIALS),"stripe": KindSpec(label="Stripe", default=_OAUTH, others=frozenset({_TOKEN})),"tiktok-ads": KindSpec(label="TikTok Ads", default=_OAUTH),- "twilio": KindSpec(label="Twilio", default=_TOKEN),+ "twilio": KindSpec(label="Twilio", default=_TOKEN, others=frozenset({_CREDENTIALS})),"twitter-ads": KindSpec(label="X Ads", default=_OAUTH),- "vercel": KindSpec(label="Vercel", default=_OAUTH, others=frozenset({_TOKEN})),+ "vercel": KindSpec(label="Vercel", default=_OAUTH, others=frozenset({_TOKEN, _CREDENTIALS})),"youtube-analytics": KindSpec(label="YouTube Analytics", default=_OAUTH),}diff --git a/posthog/integrations/kinds_generated.py b/posthog/integrations/kinds_generated.pyindex 7253484d034c..2e62841e605f 100644--- a/posthog/integrations/kinds_generated.py+++ b/posthog/integrations/kinds_generated.py@@ -116,6 +116,7 @@ class ClickupKind(KindAccessor):kind = "clickup"oauth = OAuthAccessor(kind="clickup") # the defaulttoken = AuthAccessor(kind="clickup", auth_type=AuthType.TOKEN)+ credentials = AuthAccessor(kind="clickup", auth_type=AuthType.CREDENTIALS)any = IntegrationReader(kinds=frozenset({"clickup"}))@@ -166,6 +167,7 @@ class GithubKind(KindAccessor):class GitlabKind(KindAccessor):kind = "gitlab"token = AuthAccessor(kind="gitlab", auth_type=AuthType.TOKEN) # the default+ credentials = AuthAccessor(kind="gitlab", auth_type=AuthType.CREDENTIALS)any = IntegrationReader(kinds=frozenset({"gitlab"}))@@ -184,6 +186,7 @@ class GoogleAnalyticsKind(KindAccessor):class GoogleCalendarKind(KindAccessor):kind = "google-calendar"oauth = OAuthAccessor(kind="google-calendar") # the default+ credentials = AuthAccessor(kind="google-calendar", auth_type=AuthType.CREDENTIALS)any = IntegrationReader(kinds=frozenset({"google-calendar"}))@@ -246,6 +249,7 @@ class JiraKind(KindAccessor):kind = "jira"oauth = OAuthAccessor(kind="jira") # the defaulttoken = AuthAccessor(kind="jira", auth_type=AuthType.TOKEN)+ credentials = AuthAccessor(kind="jira", auth_type=AuthType.CREDENTIALS)any = IntegrationReader(kinds=frozenset({"jira"}))@@ -270,6 +274,7 @@ class MetaAdsKind(KindAccessor):class PardotKind(KindAccessor):kind = "pardot"oauth = OAuthAccessor(kind="pardot") # the default+ credentials = AuthAccessor(kind="pardot", auth_type=AuthType.CREDENTIALS)any = IntegrationReader(kinds=frozenset({"pardot"}))@@ -357,6 +362,7 @@ class TiktokAdsKind(KindAccessor):class TwilioKind(KindAccessor):kind = "twilio"token = AuthAccessor(kind="twilio", auth_type=AuthType.TOKEN) # the default+ credentials = AuthAccessor(kind="twilio", auth_type=AuthType.CREDENTIALS)any = IntegrationReader(kinds=frozenset({"twilio"}))@@ -370,6 +376,7 @@ class VercelKind(KindAccessor):kind = "vercel"oauth = OAuthAccessor(kind="vercel") # the defaulttoken = AuthAccessor(kind="vercel", auth_type=AuthType.TOKEN)+ credentials = AuthAccessor(kind="vercel", auth_type=AuthType.CREDENTIALS)any = IntegrationReader(kinds=frozenset({"vercel"}))diff --git a/posthog/integrations/references.py b/posthog/integrations/references.pynew file mode 100644index 000000000000..8e4349907750--- /dev/null+++ b/posthog/integrations/references.py@@ -0,0 +1,60 @@+"""The string form of a reference to an integration row, for code that stores the reference outside the SDK."""++from __future__ import annotations++from uuid import UUID++from posthog.dataclasses import frozen+++@frozen+class IntegrationReference:+ """A pointer to one integration row, stored as a string.++ Rows of the `Integration` model have int ids. Rows in the credentials service get a UUID id, and+ keep the old int id as `legacy_id`. So a stored reference is a decimal string ("123") for a legacy+ id, or a canonical UUID. Parse and format a stored reference only with this class.++ The SDK accessors take int ids. A UUID reference cannot resolve yet, so callers treat it as+ "not found".+ """++ legacy_id: int | None = None+ uuid: UUID | None = None++ def __post_init__(self) -> None:+ if (self.legacy_id is None) == (self.uuid is None):+ raise ValueError("An integration reference needs exactly one of legacy_id and uuid")+ # bool is an int subclass, so `True` would format as "True" and never parse back.+ if self.legacy_id is not None and (type(self.legacy_id) is not int or self.legacy_id < 0):+ raise ValueError("A legacy integration id must be a non-negative int")+ if self.uuid is not None and not isinstance(self.uuid, UUID):+ raise ValueError("The uuid of an integration reference must be a UUID")++ @classmethod+ def from_legacy_id(cls, legacy_id: int) -> IntegrationReference:+ return cls(legacy_id=legacy_id)++ @classmethod+ def parse(cls, value: str) -> IntegrationReference:+ """Read a stored reference. Raises ValueError for any string that `str()` does not give.++ Only the canonical forms parse: ASCII digits with no sign and no leading zero, or a lowercase+ hyphenated UUID. So each row has exactly one stored form, and an equality query finds it.+ """+ if not isinstance(value, str):+ raise ValueError("An integration reference must be a string")+ if value.isascii() and value.isdigit():+ if len(value) > 1 and value.startswith("0"):+ raise ValueError("An integration reference must not have a leading zero")+ return cls(legacy_id=int(value))+ try:+ uuid = UUID(value)+ except ValueError:+ raise ValueError("An integration reference must be a decimal id or a UUID") from None+ if str(uuid) != value:+ raise ValueError("An integration reference UUID must be in lowercase hyphenated form")+ return cls(uuid=uuid)++ def __str__(self) -> str:+ return str(self.legacy_id) if self.legacy_id is not None else str(self.uuid)diff --git a/posthog/integrations/test/test_references.py b/posthog/integrations/test/test_references.pynew file mode 100644index 000000000000..307aa26bb283--- /dev/null+++ b/posthog/integrations/test/test_references.py@@ -0,0 +1,83 @@+from typing import Any+from uuid import UUID++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.integrations import IntegrationReference++UUID_TEXT = "0b7e8c3a-5f4d-4e2a-9c1b-2d3e4f5a6b7c"+++class TestIntegrationReference(SimpleTestCase):+ @parameterized.expand(+ [+ ("zero", "0", IntegrationReference(legacy_id=0)),+ ("small", "7", IntegrationReference(legacy_id=7)),+ ("int32_max", "2147483647", IntegrationReference(legacy_id=2147483647)),+ ("beyond_int64", "18446744073709551616", IntegrationReference(legacy_id=2**64)),+ ("uuid", UUID_TEXT, IntegrationReference(uuid=UUID(UUID_TEXT))),+ ]+ )+ def test_parse_reads_the_canonical_forms_and_str_writes_them_back(+ self, _name: str, value: str, expected: IntegrationReference+ ) -> None:+ reference = IntegrationReference.parse(value)++ assert reference == expected+ assert str(reference) == value++ @parameterized.expand(+ [+ ("empty", ""),+ ("space", " "),+ ("leading_space", " 7"),+ ("trailing_newline", "7\n"),+ ("plus_sign", "+7"),+ ("minus_sign", "-7"),+ ("leading_zero", "07"),+ ("double_zero", "00"),+ ("decimal_point", "7.0"),+ ("underscore", "1_000"),+ ("exponent", "1e3"),+ ("non_ascii_digits", "١٢"),+ ("superscript_digit", "²"),+ ("uuid_upper_case", UUID_TEXT.upper()),+ ("uuid_without_hyphens", UUID_TEXT.replace("-", "")),+ ("uuid_with_braces", "{" + UUID_TEXT + "}"),+ ("uuid_urn", "urn:uuid:" + UUID_TEXT),+ ("uuid_with_space", UUID_TEXT + " "),+ ("garbage", "not-a-reference"),+ ("hex_int", "0x1f"),+ ]+ )+ def test_parse_rejects_every_other_string(self, _name: str, value: str) -> None:+ with self.assertRaises(ValueError):+ IntegrationReference.parse(value)++ @parameterized.expand([("int", 7), ("none", None), ("bytes", b"7")])+ def test_parse_rejects_a_value_that_is_not_a_string(self, _name: str, value: Any) -> None:+ with self.assertRaises(ValueError):+ IntegrationReference.parse(value)++ @parameterized.expand(+ [+ ("neither", {}),+ ("both", {"legacy_id": 7, "uuid": UUID(UUID_TEXT)}),+ ("negative_id", {"legacy_id": -1}),+ ("bool_id", {"legacy_id": True}),+ ("string_id", {"legacy_id": "7"}),+ ("string_uuid", {"uuid": UUID_TEXT}),+ ]+ )+ def test_constructor_rejects_an_invalid_reference(self, _name: str, kwargs: dict[str, Any]) -> None:+ with self.assertRaises(ValueError):+ IntegrationReference(**kwargs)++ @parameterized.expand([("zero", 0), ("int", 12), ("large", 2**40)])+ def test_from_legacy_id_round_trips(self, _name: str, legacy_id: int) -> None:+ reference = IntegrationReference.from_legacy_id(legacy_id)++ assert (reference.legacy_id, reference.uuid) == (legacy_id, None)+ assert IntegrationReference.parse(str(reference)) == referencediff --git a/posthog/models/integration/__init__.py b/posthog/models/integration/__init__.pyindex 67d96a8046ce..19c89fc54ad0 100644--- a/posthog/models/integration/__init__.py+++ b/posthog/models/integration/__init__.py@@ -81,6 +81,8 @@ from .linear import LinearIntegration, LinearIntegrationError, LinearRateLimitedfrom .linkedin_ads import LinkedInAdsIntegrationfrom .meta import InstagramIntegration, MetaAdsIntegration, MetaGraphIntegrationfrom .model import (+ PUBLIC_INTEGRATION_KIND_CHOICES,+ WAREHOUSE_SOURCE_TYPE_CONFIG_KEY,Integration,IntegrationModelManager,IntegrationQuerySet,@@ -207,6 +209,8 @@ __all__ = ["OauthClientCredentials","OauthConfig","POSTHOG_SLACK_SCOPE",+ "PUBLIC_INTEGRATION_KIND_CHOICES",+ "WAREHOUSE_SOURCE_TYPE_CONFIG_KEY","OAUTH_CLIENT_CREDENTIAL_KEYS","SALESFORCE_OAUTH_KINDS","POSTHOG_CONNECT_KIND",diff --git a/posthog/models/integration/model.py b/posthog/models/integration/model.pyindex 46568df96364..bd2261797fbe 100644--- a/posthog/models/integration/model.py+++ b/posthog/models/integration/model.py@@ -22,6 +22,7 @@ from .auth_types import (AuthRequirement,AuthTypeSelector,IntegrationAuthType,+ catalogued_kinds,config_for_write,default_auth_type,effective_auth_type,@@ -100,6 +101,13 @@ def _decrypted_sensitive_value(integration: "Integration", field_name: str) -> sreturn recovered+# Marks a row that a data warehouse source created from the fields a user typed in. The value is the+# source type, so a client can show the source's name and icon for a kind it does not know. The row+# holds `sensitive_config["fields"]` in the source's own field shape, not in the shape that other+# code of the kind reads. Hog functions must never get such a row as an input.+WAREHOUSE_SOURCE_TYPE_CONFIG_KEY = "warehouse_source_type"++class IntegrationQuerySet(models.QuerySet["Integration"]):# Set by `_with_auth`. None means the query did not state its auth types._auth_requirement: AuthRequirement | None = None@@ -234,8 +242,13 @@ class _AllRowsManager(IntegrationModelManager):def integration_kind_choices() -> list[tuple[str, str | Promise]]:- # Callable so growing the enum doesn't generate a no-op migration.- return list(Integration.IntegrationKind.choices)+ # Callable so growing the enum doesn't generate a no-op migration. Kinds that a product registers+ # with `register_kind_auth_types` (the warehouse source credential kinds) are valid stored kinds+ # too, but they stay out of `IntegrationKind` and so out of the public API enum.+ choices: list[tuple[str, str | Promise]] = list(Integration.IntegrationKind.choices)+ known = {value for value, _ in choices}+ choices += [(kind, kind) for kind in sorted(catalogued_kinds()) if kind not in known]+ return choicesclass Integration(models.Model):@@ -349,9 +362,13 @@ class Integration(models.Model):"""The stored `config["auth_type"]`, or the default auth type of the kind when the key is missing."""return effective_auth_type(self.kind, self.config)+ @property+ def holds_warehouse_source_fields(self) -> bool:+ return isinstance(self.config, dict) and WAREHOUSE_SOURCE_TYPE_CONFIG_KEY in self.config+@propertydef display_name(self) -> str:- if self.auth_type != default_auth_type(self.kind):+ if self.holds_warehouse_source_fields or self.auth_type != default_auth_type(self.kind):# The branches below read the config shape of the default auth type.return self.config.get("display_name") or f"ID: {self.integration_id}"if self.kind == "twitter-ads":@@ -470,3 +487,8 @@ def defer_repository_cache_fields[QuerySetT: models.QuerySet[Integration]](query@database_sync_to_asyncdef aget_integration_by_id(integration_id: str, team_id: int) -> Integration | None:return Integration.objects.get(id=integration_id, team_id=team_id)+++# The kinds that an API request can name. A kind that a product registers (a warehouse source+# credential kind) is stored data only, so the generated API enum stays small.+PUBLIC_INTEGRATION_KIND_CHOICES = list(Integration.IntegrationKind.choices)diff --git a/posthog/session_recordings/session_recording_external_reference_api.py b/posthog/session_recordings/session_recording_external_reference_api.pyindex 6fc3a292999c..974ef73a0a3e 100644--- a/posthog/session_recordings/session_recording_external_reference_api.py+++ b/posthog/session_recordings/session_recording_external_reference_api.py@@ -30,6 +30,8 @@ logger = structlog.get_logger(__name__)class SessionRecordingExternalReferenceIntegrationSerializer(serializers.ModelSerializer):"""Read-only serializer for Integration info embedded in external references"""+ kind = serializers.CharField(read_only=True, help_text="The provider of the integration, for example 'github'.")+class Meta:model = Integrationfields = ["id", "kind", "display_name"]diff --git a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambrindex 6bc57a076cb4..0ed396915157 100644--- a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr+++ b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr@@ -892,6 +892,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",diff --git a/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambr b/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambrindex 8b8a64c7c48a..527b80d08a5b 100644--- a/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambr+++ b/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambr@@ -658,6 +658,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -1326,6 +1327,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -1990,6 +1992,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -2654,6 +2657,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -3322,6 +3326,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -3990,6 +3995,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -4658,6 +4664,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -5018,6 +5025,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -5705,6 +5713,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -6495,6 +6504,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -7362,6 +7372,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -8062,6 +8073,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -8440,6 +8452,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -8820,6 +8833,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -9496,6 +9510,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -10214,6 +10229,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -10993,6 +11009,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -11668,6 +11685,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",@@ -11778,6 +11796,7 @@"posthog_externaldatasource"."source_type","posthog_externaldatasource"."api_version","posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."credentials_integration_id","posthog_externaldatasource"."connection_metadata","posthog_externaldatasource"."are_tables_created","posthog_externaldatasource"."prefix",diff --git a/products/batch_exports/backend/integration_usages.py b/products/batch_exports/backend/integration_usages.pynew file mode 100644index 000000000000..d8f6fe7b8b72--- /dev/null+++ b/products/batch_exports/backend/integration_usages.py@@ -0,0 +1,14 @@+"""The batch exports that write through an integration row. The integrations SDK loads this module."""++from posthog.integrations import IntegrationUsage++from products.batch_exports.backend.facade.api import list_batch_exports_using_integration++BATCH_EXPORT_USAGE_TYPE = "batch_export"+++def integration_usages(team_id: int, integration_id: int) -> list[IntegrationUsage]:+ return [+ IntegrationUsage(type=BATCH_EXPORT_USAGE_TYPE, id=str(export.id), name=export.name or str(export.id))+ for export in list_batch_exports_using_integration(team_id=team_id, integration_id=integration_id)+ ]diff --git a/products/cdp/backend/integration_usages.py b/products/cdp/backend/integration_usages.pynew file mode 100644index 000000000000..fb68fb497f72--- /dev/null+++ b/products/cdp/backend/integration_usages.py@@ -0,0 +1,14 @@+"""The enabled hog functions that use an integration row. The integrations SDK loads this module."""++from posthog.integrations import IntegrationUsage++from products.cdp.backend.services.integration_usage import get_enabled_hog_functions_using_integration++HOG_FUNCTION_USAGE_TYPE = "hog_function"+++def integration_usages(team_id: int, integration_id: int) -> list[IntegrationUsage]:+ return [+ IntegrationUsage(type=HOG_FUNCTION_USAGE_TYPE, id=str(function.id), name=function.name or str(function.id))+ for function in get_enabled_hog_functions_using_integration(team_id=team_id, integration_id=integration_id)+ ]diff --git a/products/cdp/backend/test/test_validation.py b/products/cdp/backend/test/test_validation.pyindex 6b8c3cfa1ee1..81ad0df619de 100644--- a/products/cdp/backend/test/test_validation.py+++ b/products/cdp/backend/test/test_validation.py@@ -10,7 +10,7 @@ from rest_framework.exceptions import ValidationErrorfrom posthog.hogql import ast-from posthog.models.integration import Integration+from posthog.models.integration import ANY, WAREHOUSE_SOURCE_TYPE_CONFIG_KEY, Integrationfrom products.cdp.backend.filters import RUNTIME_CONTRACTfrom products.cdp.backend.validation import (@@ -599,25 +599,48 @@ class TestHogFunctionValidation(ClickhouseTestMixin, APIBaseTest, QueryMatchingT@parameterized.expand([- ("single_slack", "integration", "slack"),- ("multi_slack", "integration_multi", "slack"),- ("single_posthog_connection", "integration", "posthog"),- ("multi_posthog_connection", "integration_multi", "posthog"),+ ("single_slack", "integration", "slack", None, None),+ ("multi_slack", "integration_multi", "slack", None, None),+ ("single_posthog_connection", "integration", "posthog", None, "PostHog connection"),+ ("multi_posthog_connection", "integration_multi", "posthog", None, "PostHog connection"),+ # Warehouse source rows are blocked by the marker, whatever their kind and auth type.+ ("single_warehouse_default_auth", "integration", "postgresql", None, "can't be used as a function input"),+ ("multi_warehouse_default_auth", "integration_multi", "postgresql", None, "can't be used"),+ ("warehouse_typed_in_auth", "integration", "stripe", "token", "can't be used as a function input"),+ ("warehouse_generated_kind", "integration", "ably", None, "can't be used as a function input"),])- def test_integration_input_rejects_a_posthog_connection(self, _name, item_type, kind):- integration = Integration.objects.create(team=self.team, kind=kind, created_by=self.user)+ def test_integration_input_rejects_a_posthog_connection_or_warehouse_credentials(+ self, _name, item_type, kind, auth_type, expected_error+ ):+ config = (+ {} if expected_error in (None, "PostHog connection") else {WAREHOUSE_SOURCE_TYPE_CONFIG_KEY: "Postgres"}+ )+ if auth_type:+ config["auth_type"] = auth_type+ integration = Integration.objects._with_auth(ANY).create(+ team=self.team, kind=kind, config=config, created_by=self.user+ )value = integration.id if item_type == "integration" else [integration.id]inputs_schema = [{"key": "connection", "type": item_type, "integration": "slack", "required": True}]inputs = {"connection": {"value": value}}context_extra = {"get_team": lambda: self.team}- if kind == "slack":+ if expected_error is None:assert validate_inputs(inputs_schema, inputs, context_extra=context_extra)["connection"]["value"] == valueelse:with pytest.raises(ValidationError) as ctx:validate_inputs(inputs_schema, inputs, context_extra=context_extra)- assert "PostHog connection" in str(ctx.value.detail)+ assert expected_error in str(ctx.value.detail)++ def test_integration_input_allows_an_unmarked_row_of_a_warehouse_kind(self):+ integration = Integration.objects.create(team=self.team, kind="postgresql", config={"host": "db.example.com"})+ inputs_schema = [{"key": "connection", "type": "integration", "integration": "postgresql", "required": True}]+ inputs = {"connection": {"value": integration.id}}++ validated = validate_inputs(inputs_schema, inputs, context_extra={"get_team": lambda: self.team})++ assert validated["connection"]["value"] == integration.iddef _create_email_integration(self, domain="posthog.com"):return Integration.objects.create(diff --git a/products/cdp/backend/validation.py b/products/cdp/backend/validation.pyindex 521fe23f5325..c386c1a5a36c 100644--- a/products/cdp/backend/validation.py+++ b/products/cdp/backend/validation.py@@ -19,6 +19,7 @@ from posthog.hogql.parser import parse_program, parse_string_templatefrom posthog.hogql.visitor import TraversingVisitorfrom posthog.integrations import IntegrationManager+from posthog.models.integration import POSTHOG_CONNECT_KIND, WAREHOUSE_SOURCE_TYPE_CONFIG_KEYfrom posthog.models.team.team import Teamfrom posthog.models.user import User@@ -98,10 +99,18 @@ def _validate_not_posthog_connection(integration_ids: list[int], context: dict)get_team = context.get("get_team")if get_team is None or not integration_ids:return- if IntegrationManager.posthog.any.get_many(get_team().id, integration_ids):+ # Warehouse source rows must be read too, so the guard below can reject them.+ rows = IntegrationManager.any.with_source_rows().get_many(get_team().id, integration_ids).values()+ if any(row.kind == POSTHOG_CONNECT_KIND for row in rows):raise serializers.ValidationError({"input": "A PostHog connection can't be used as a function input. Choose a different integration."})+ # A row that a data warehouse source created holds the source's typed-in credentials (passwords,+ # keys). The runtime passes an input's secrets to the function code, so no function may use it.+ if any(WAREHOUSE_SOURCE_TYPE_CONFIG_KEY in (row.config or {}) for row in rows):+ raise serializers.ValidationError(+ {"input": "This integration can't be used as a function input. Choose a different integration."}+ )def _validate_email_sender_override(from_value: dict, context: dict) -> None:diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.tsindex 94a15a2a00e8..aae92abb7ec8 100644--- a/products/desktop/packages/api-client/src/generated.ts+++ b/products/desktop/packages/api-client/src/generated.ts@@ -16571,115 +16571,15 @@ export namespace Schemas {* * `credentials` - Credentials*/export type IntegrationAuthTypeEnum = "oauth" | "token" | "credentials";- /**- * * `anthropic` - Anthropic- * * `apple-ads` - Apple Ads- * * `apns` - Apple Push- * * `aws-redshift` - Aws Redshift- * * `aws-s3` - Aws S3- * * `azure-blob` - Azure Blob- * * `bing-ads` - Bing Ads- * * `clickup` - Clickup- * * `customerio-app` - Customerio App- * * `customerio-track` - Customerio Track- * * `customerio-webhook` - Customerio Webhook- * * `databricks` - Databricks- * * `email` - Email- * * `firebase` - Firebase- * * `github` - Github- * * `gitlab` - Gitlab- * * `google-ads` - Google Ads- * * `google-analytics` - Google Analytics- * * `google-calendar` - Google Calendar- * * `google-cloud-service-account` - Google Cloud Service Account- * * `google-cloud-storage` - Google Cloud Storage- * * `google-pubsub` - Google Pubsub- * * `google-search-console` - Google Search Console- * * `google-sheets` - Google Sheets- * * `helpscout` - Helpscout- * * `hubspot` - Hubspot- * * `instagram` - Instagram- * * `intercom` - Intercom- * * `jira` - Jira- * * `linear` - Linear- * * `linkedin-ads` - Linkedin Ads- * * `meta-ads` - Meta Ads- * * `pardot` - Pardot- * * `pinterest-ads` - Pinterest Ads- * * `postgresql` - Postgresql- * * `posthog` - Posthog- * * `reddit-ads` - Reddit Ads- * * `twitter-ads` - Twitter Ads- * * `resend` - Resend- * * `s3-compatible` - S3 Compatible- * * `salesforce` - Salesforce- * * `slack` - Slack- * * `slack-posthog-code` - Slack Posthog Code- * * `snapchat` - Snapchat- * * `snowflake` - Snowflake- * * `stripe` - Stripe- * * `tiktok-ads` - Tiktok Ads- * * `twilio` - Twilio- * * `vercel` - Vercel- * * `youtube-analytics` - Youtube Analytics- */- export type IntegrationKindEnum =- | "anthropic"- | "apple-ads"- | "apns"- | "aws-redshift"- | "aws-s3"- | "azure-blob"- | "bing-ads"- | "clickup"- | "customerio-app"- | "customerio-track"- | "customerio-webhook"- | "databricks"- | "email"- | "firebase"- | "github"- | "gitlab"- | "google-ads"- | "google-analytics"- | "google-calendar"- | "google-cloud-service-account"- | "google-cloud-storage"- | "google-pubsub"- | "google-search-console"- | "google-sheets"- | "helpscout"- | "hubspot"- | "instagram"- | "intercom"- | "jira"- | "linear"- | "linkedin-ads"- | "meta-ads"- | "pardot"- | "pinterest-ads"- | "postgresql"- | "posthog"- | "reddit-ads"- | "twitter-ads"- | "resend"- | "s3-compatible"- | "salesforce"- | "slack"- | "slack-posthog-code"- | "snapchat"- | "snowflake"- | "stripe"- | "tiktok-ads"- | "twilio"- | "vercel"- | "youtube-analytics";/*** Standard Integration serializer.*/export type IntegrationConfig = {id: number;- kind: IntegrationKindEnum;+ /**+ * The provider of the integration, for example 'slack' or 'github'. A create accepts only the kinds that PostHog connects here. Data warehouse sources also store their typed-in credentials as integrations, under a kind per source type.+ */+ kind: string;/*** How this integration authenticates with the provider: `oauth` for a connection the provider manages (an OAuth grant or an app installation), `token` for one static secret, or `credentials` for several typed-in fields. A kind can have several auth types.*diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.tsindex 5968c31a9b8e..06cf71e3a134 100644--- a/products/integrations/frontend/generated/api.schemas.ts+++ b/products/integrations/frontend/generated/api.schemas.ts@@ -150,6 +150,71 @@ export interface RoleLookupResponseApi {reference: RoleExternalReferenceApi | null}+/**+ * * `oauth` - OAuth+ * * `token` - Token+ * * `credentials` - Credentials+ */+export type IntegrationAuthTypeEnumApi = (typeof IntegrationAuthTypeEnumApi)[keyof typeof IntegrationAuthTypeEnumApi]++export const IntegrationAuthTypeEnumApi = {+ Oauth: 'oauth',+ Token: 'token',+ Credentials: 'credentials',+} as const++/**+ * * `connected` - connected+ * * `unavailable` - unavailable+ */+export type InstallationStatusEnumApi = (typeof InstallationStatusEnumApi)[keyof typeof InstallationStatusEnumApi]++export const InstallationStatusEnumApi = {+ Connected: 'connected',+ Unavailable: 'unavailable',+} as const++/**+ * Standard Integration serializer.+ */+export interface IntegrationConfigApi {+ readonly id: number+ /**+ * The provider of the integration, for example 'slack' or 'github'. A create accepts only the kinds that PostHog connects here. Data warehouse sources also store their typed-in credentials as integrations, under a kind per source type.+ * @maxLength 32+ */+ kind: string+ /** How this integration authenticates with the provider: `oauth` for a connection the provider manages (an OAuth grant or an app installation), `token` for one static secret, or `credentials` for several typed-in fields. A kind can have several auth types.+ *+ * * `oauth` - OAuth+ * * `token` - Token+ * * `credentials` - Credentials */+ readonly auth_type: IntegrationAuthTypeEnumApi+ config?: unknown+ readonly created_at: string+ readonly created_by: UserBasicApi+ readonly errors: string+ readonly display_name: string+ /** Slack only: whether reconnecting can request the files:write scope. */+ readonly files_write_requestable: boolean+ /**+ * GitHub only, null otherwise. Whether another project's GitHub integration references the same App installation. When false, disconnecting this integration also uninstalls the GitHub App from the connected account or organization and removes personal GitHub connections that share it.+ * @nullable+ */+ readonly installation_shared: boolean | null+ /** GitHub only, null otherwise. `unavailable` means the App was uninstalled or suspended on GitHub and PostHog can no longer mint tokens for it; `connected` otherwise. */+ readonly installation_status: InstallationStatusEnumApi | null+}++export interface PaginatedIntegrationConfigListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: IntegrationConfigApi[]+}+/*** * `anthropic` - Anthropic* * `apple-ads` - Apple Ads@@ -258,34 +323,62 @@ export const IntegrationKindEnumApi = {} as const/**- * * `oauth` - OAuth- * * `token` - Token- * * `credentials` - Credentials- */-export type IntegrationAuthTypeEnumApi = (typeof IntegrationAuthTypeEnumApi)[keyof typeof IntegrationAuthTypeEnumApi]--export const IntegrationAuthTypeEnumApi = {- Oauth: 'oauth',- Token: 'token',- Credentials: 'credentials',-} as const--/**- * * `connected` - connected- * * `unavailable` - unavailable+ * The request schema of a create. A create accepts only the public kinds, so the schema lists them.*/-export type InstallationStatusEnumApi = (typeof InstallationStatusEnumApi)[keyof typeof InstallationStatusEnumApi]--export const InstallationStatusEnumApi = {- Connected: 'connected',- Unavailable: 'unavailable',-} as const--/**- * Standard Integration serializer.- */-export interface IntegrationConfigApi {+export interface IntegrationConfigCreateApi {readonly id: number+ /** The provider of the integration, for example 'slack' or 'github'.+ *+ * * `anthropic` - Anthropic+ * * `apple-ads` - Apple Ads+ * * `apns` - Apple Push+ * * `aws-redshift` - Aws Redshift+ * * `aws-s3` - Aws S3+ * * `azure-blob` - Azure Blob+ * * `bing-ads` - Bing Ads+ * * `clickup` - Clickup+ * * `customerio-app` - Customerio App+ * * `customerio-track` - Customerio Track+ * * `customerio-webhook` - Customerio Webhook+ * * `databricks` - Databricks+ * * `email` - Email+ * * `firebase` - Firebase+ * * `github` - Github+ * * `gitlab` - Gitlab+ * * `google-ads` - Google Ads+ * * `google-analytics` - Google Analytics+ * * `google-calendar` - Google Calendar+ * * `google-cloud-service-account` - Google Cloud Service Account+ * * `google-cloud-storage` - Google Cloud Storage+ * * `google-pubsub` - Google Pubsub+ * * `google-search-console` - Google Search Console+ * * `google-sheets` - Google Sheets+ * * `helpscout` - Helpscout+ * * `hubspot` - Hubspot+ * * `instagram` - Instagram+ * * `intercom` - Intercom+ * * `jira` - Jira+ * * `linear` - Linear+ * * `linkedin-ads` - Linkedin Ads+ * * `meta-ads` - Meta Ads+ * * `pardot` - Pardot+ * * `pinterest-ads` - Pinterest Ads+ * * `postgresql` - Postgresql+ * * `posthog` - Posthog+ * * `reddit-ads` - Reddit Ads+ * * `twitter-ads` - Twitter Ads+ * * `resend` - Resend+ * * `s3-compatible` - S3 Compatible+ * * `salesforce` - Salesforce+ * * `slack` - Slack+ * * `slack-posthog-code` - Slack Posthog Code+ * * `snapchat` - Snapchat+ * * `snowflake` - Snowflake+ * * `stripe` - Stripe+ * * `tiktok-ads` - Tiktok Ads+ * * `twilio` - Twilio+ * * `vercel` - Vercel+ * * `youtube-analytics` - Youtube Analytics */kind: IntegrationKindEnumApi/** How this integration authenticates with the provider: `oauth` for a connection the provider manages (an OAuth grant or an app installation), `token` for one static secret, or `credentials` for several typed-in fields. A kind can have several auth types.*@@ -309,15 +402,6 @@ export interface IntegrationConfigApi {readonly installation_status: InstallationStatusEnumApi | null}-export interface PaginatedIntegrationConfigListApi {- count: number- /** @nullable */- next?: string | null- /** @nullable */- previous?: string | null- results: IntegrationConfigApi[]-}-export interface SlackChannelApi {/** Slack channel ID (e.g. C0123ABC) — pass to cdp-functions inputs.channel. */id: string@@ -363,7 +447,11 @@ export interface SlackChannelsResponseApi {*/export interface PatchedIntegrationConfigApi {readonly id?: number- kind?: IntegrationKindEnumApi+ /**+ * The provider of the integration, for example 'slack' or 'github'. A create accepts only the kinds that PostHog connects here. Data warehouse sources also store their typed-in credentials as integrations, under a kind per source type.+ * @maxLength 32+ */+ kind?: string/** How this integration authenticates with the provider: `oauth` for a connection the provider manages (an OAuth grant or an app installation), `token` for one static secret, or `credentials` for several typed-in fields. A kind can have several auth types.** * `oauth` - OAuthdiff --git a/products/integrations/frontend/generated/api.ts b/products/integrations/frontend/generated/api.tsindex 7cea480691f2..8592d340a2a0 100644--- a/products/integrations/frontend/generated/api.ts+++ b/products/integrations/frontend/generated/api.ts@@ -26,6 +26,7 @@ import type {IntegrationAccessRequestResponseApi,IntegrationAssigneesResponseApi,IntegrationConfigApi,+ IntegrationConfigCreateApi,IntegrationsChannelsRetrieveParams,IntegrationsDomainConnectCheckRetrieveParams,IntegrationsEmailStatusRetrieveParams,@@ -229,14 +230,14 @@ export const getIntegrationsCreateUrl = (projectId: string) => {export const integrationsCreate = async (projectId: string,- integrationConfigApi: NonReadonly<IntegrationConfigApi>,+ integrationConfigCreateApi: NonReadonly<IntegrationConfigCreateApi>,options?: RequestInit): Promise<IntegrationConfigApi> => {return apiMutator<IntegrationConfigApi>(getIntegrationsCreateUrl(projectId), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(integrationConfigApi),+ body: JSON.stringify(integrationConfigCreateApi),})}diff --git a/products/integrations/frontend/generated/api.zod.ts b/products/integrations/frontend/generated/api.zod.tsindex 6252f22e66be..d8aa94c806d0 100644--- a/products/integrations/frontend/generated/api.zod.ts+++ b/products/integrations/frontend/generated/api.zod.ts@@ -115,69 +115,24 @@ export const IntegrationsCreateBody = /* @__PURE__ */ zod]).describe('\* `anthropic` - Anthropic\n\* `apple-ads` - Apple Ads\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'+ )+ .describe(+ "The provider of the integration, for example 'slack' or 'github'.\n\n\* `anthropic` - Anthropic\n\* `apple-ads` - Apple Ads\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics"),config: zod.unknown().optional(),})- .describe('Standard Integration serializer.')+ .describe('The request schema of a create. A create accepts only the public kinds, so the schema lists them.')++export const integrationsEmailPartialUpdateBodyKindMax = 32export const IntegrationsEmailPartialUpdateBody = /* @__PURE__ */ zod.object({kind: zod- .enum([- 'anthropic',- 'apple-ads',- 'apns',- 'aws-redshift',- 'aws-s3',- 'azure-blob',- 'bing-ads',- 'clickup',- 'customerio-app',- 'customerio-track',- 'customerio-webhook',- 'databricks',- 'email',- 'firebase',- 'github',- 'gitlab',- 'google-ads',- 'google-analytics',- 'google-calendar',- 'google-cloud-service-account',- 'google-cloud-storage',- 'google-pubsub',- 'google-search-console',- 'google-sheets',- 'helpscout',- 'hubspot',- 'instagram',- 'intercom',- 'jira',- 'linear',- 'linkedin-ads',- 'meta-ads',- 'pardot',- 'pinterest-ads',- 'postgresql',- 'posthog',- 'reddit-ads',- 'twitter-ads',- 'resend',- 's3-compatible',- 'salesforce',- 'slack',- 'slack-posthog-code',- 'snapchat',- 'snowflake',- 'stripe',- 'tiktok-ads',- 'twilio',- 'vercel',- 'youtube-analytics',- ])+ .string()+ .max(integrationsEmailPartialUpdateBodyKindMax).optional().describe(- '\* `anthropic` - Anthropic\n\* `apple-ads` - Apple Ads\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'+ "The provider of the integration, for example 'slack' or 'github'. A create accepts only the kinds that PostHog connects here. Data warehouse sources also store their typed-in credentials as integrations, under a kind per source type."),config: zod.unknown().optional(),})@@ -215,63 +170,15 @@ export const IntegrationsPushTokensCreateBody = /* @__PURE__ */ zod.object({* The backend resolves the domain, template variables, and service ID* based on context, then builds the signed apply URL.*/+export const integrationsDomainConnectApplyUrlCreateBodyKindMax = 32+export const IntegrationsDomainConnectApplyUrlCreateBody = /* @__PURE__ */ zod.object({kind: zod- .enum([- 'anthropic',- 'apple-ads',- 'apns',- 'aws-redshift',- 'aws-s3',- 'azure-blob',- 'bing-ads',- 'clickup',- 'customerio-app',- 'customerio-track',- 'customerio-webhook',- 'databricks',- 'email',- 'firebase',- 'github',- 'gitlab',- 'google-ads',- 'google-analytics',- 'google-calendar',- 'google-cloud-service-account',- 'google-cloud-storage',- 'google-pubsub',- 'google-search-console',- 'google-sheets',- 'helpscout',- 'hubspot',- 'instagram',- 'intercom',- 'jira',- 'linear',- 'linkedin-ads',- 'meta-ads',- 'pardot',- 'pinterest-ads',- 'postgresql',- 'posthog',- 'reddit-ads',- 'twitter-ads',- 'resend',- 's3-compatible',- 'salesforce',- 'slack',- 'slack-posthog-code',- 'snapchat',- 'snowflake',- 'stripe',- 'tiktok-ads',- 'twilio',- 'vercel',- 'youtube-analytics',- ])+ .string()+ .max(integrationsDomainConnectApplyUrlCreateBodyKindMax).describe(- '\* `anthropic` - Anthropic\n\* `apple-ads` - Apple Ads\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'+ "The provider of the integration, for example 'slack' or 'github'. A create accepts only the kinds that PostHog connects here. Data warehouse sources also store their typed-in credentials as integrations, under a kind per source type."),config: zod.unknown().optional(),})diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex 8b8fb2280945..748d926cb60f 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -207,6 +207,7 @@ export interface taskTrackerSceneLogicValues {composerOverride: ComposerOverride | null // composerOverrideLogicseed: ComposerSeed | null // composerSeedLogicfeatureFlags: FeatureFlagsSet // featureFlagLogic+ githubIntegrations: IntegrationType[] // integrationsLogicintegrations: IntegrationType[] | null // integrationsLogiccatalogue: ModelChoiceApi[] // modelCatalogueLogiccurrentProjectId: number | null // projectLogic@@ -524,7 +525,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([tasksLogic,['tasks', 'repositories', 'taskListParams'],integrationsLogic,- ['integrations'],+ ['integrations', 'githubIntegrations'],attachedContextLogic,['contextItems'],aiConsentLogic,@@ -937,7 +938,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([if (values.newTaskData.repositoryConfig.integrationId) {return}- const githubIntegrations = values.integrations?.filter((integration) => integration.kind === 'github') ?? []+ const githubIntegrations = values.githubIntegrationsif (githubIntegrations.length === 0) {return}diff --git a/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.tsindex a484b0f813a7..fee3ad645213 100644--- a/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts+++ b/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts@@ -33,7 +33,7 @@ function formValuesFromRepo(repo: RepoApi): RepoFormValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface visualReviewSettingsSceneLogicValues {getGitHubRepositoriesFull: (integrationId: number) => GitHubRepoApi[] // integrationsLogic- integrations: IntegrationType[] | null // integrationsLogic+ githubIntegrations: IntegrationType[] // integrationsLogiccurrentProjectId: number | string // teamLogicavailableRepos: GitHubRepoApi[]breadcrumbs: Breadcrumb[]@@ -99,11 +99,11 @@ export interface visualReviewSettingsSceneLogicMeta {editingRepo: (repos: RepoApi[], editingRepoId: string | null) => RepoApi | nullhasChanges: (formValues: RepoFormValues, editingRepo: RepoApi | null) => booleanavailableRepos: (- integrations: IntegrationType[] | null,+ githubIntegrations: IntegrationType[],getGitHubRepositoriesFull: (integrationId: number) => GitHubRepoApi[] // integrationsLogic) => GitHubRepoApi[]existingRepoNames: (repos: RepoApi[]) => Set<string>- githubManageAccessUrl: (integrations: IntegrationType[] | null) => string | null+ githubManageAccessUrl: (githubIntegrations: IntegrationType[]) => string | null}}@@ -118,7 +118,12 @@ export const visualReviewSettingsSceneLogic = kea<visualReviewSettingsSceneLogicpath(['products', 'visual_review', 'frontend', 'scenes', 'visualReviewSettingsSceneLogic']),connect(() => ({- values: [integrationsLogic, ['integrations', 'getGitHubRepositoriesFull'], teamLogic, ['currentProjectId']],+ values: [+ integrationsLogic,+ ['githubIntegrations', 'getGitHubRepositoriesFull'],+ teamLogic,+ ['currentProjectId'],+ ],actions: [integrationsLogic, ['loadIntegrationsSuccess']],})),@@ -194,14 +199,12 @@ export const visualReviewSettingsSceneLogic = kea<visualReviewSettingsSceneLogic},],availableRepos: [- (s) => [s.integrations, s.getGitHubRepositoriesFull],+ (s) => [s.githubIntegrations, s.getGitHubRepositoriesFull],(- integrations: any[] | null,+ githubIntegrations: IntegrationType[],getGitHubRepositoriesFull: (id: number) => GitHubRepoApi[]): GitHubRepoApi[] => {const repos: GitHubRepoApi[] = []- const githubIntegrations = integrations?.filter((i: { kind: string }) => i.kind === 'github') || []-for (const integration of githubIntegrations) {const integrationRepos = getGitHubRepositoriesFull(integration.id) || []repos.push(...integrationRepos)@@ -214,9 +217,9 @@ export const visualReviewSettingsSceneLogic = kea<visualReviewSettingsSceneLogic(repos: RepoApi[]): Set<string> => new Set(repos.map((r) => r.repo_full_name)),],githubManageAccessUrl: [- (s) => [s.integrations],- (integrations: any[] | null): string | null => {- const github = integrations?.find((i: { kind: string }) => i.kind === 'github')+ (s) => [s.githubIntegrations],+ (githubIntegrations: IntegrationType[]): string | null => {+ const github = githubIntegrations[0]const installationId = github?.config?.installation_idif (installationId) {const accountType = github?.config?.account?.type@@ -248,8 +251,7 @@ export const visualReviewSettingsSceneLogic = kea<visualReviewSettingsSceneLogiclisteners(({ values, actions }) => ({loadIntegrationsSuccess: () => {- const githubIntegrations = values.integrations?.filter((i: { kind: string }) => i.kind === 'github') || []- for (const integration of githubIntegrations) {+ for (const integration of values.githubIntegrations) {integrationsLogic.actions.loadGitHubRepositories(integration.id)}},diff --git a/products/warehouse_sources/backend/facade/contracts.py b/products/warehouse_sources/backend/facade/contracts.pyindex d1bc206fe376..029e49d4f160 100644--- a/products/warehouse_sources/backend/facade/contracts.py+++ b/products/warehouse_sources/backend/facade/contracts.py@@ -16,6 +16,7 @@ demand map). The HogQL system-table model classes cross the boundary as objects``facade/hogql.py``, and temporal/source wiring via ``facade/temporal.py`` — not here."""+from collections.abc import Sequencefrom dataclasses import fieldfrom datetime import datetime, time, timedeltafrom typing import Any@@ -23,6 +24,27 @@ from uuid import UUIDfrom pydantic.dataclasses import dataclass+from posthog.integrations import IntegrationUsage++# The request flag that confirms an edit of credentials that other sources or products also use.+UPDATE_SHARED_CREDENTIALS_PARAM = "update_shared_credentials"++# The `IntegrationUsage.type` of a warehouse source that uses an integration row.+WAREHOUSE_SOURCE_USAGE_TYPE = "warehouse_source"+++class SharedCredentialsError(Exception):+ """An edit would change a credentials row that other sources or products also use.++ `usages` holds the other users, as the integrations SDK reports them. The API returns them in a+ 409 response, and the request can confirm with `update_shared_credentials`.+ """++ def __init__(self, integration_id: int, usages: Sequence[IntegrationUsage]) -> None:+ super().__init__(f"Integration {integration_id} is also used by {len(usages)} other objects")+ self.integration_id = integration_id+ self.usages = tuple(usages)+class UnsupportedSyncTypeError(ValueError):"""The stored sync type is not a mode PostHog can run."""@@ -349,3 +371,12 @@ class UploadReadSettings:columns: dict[str, Any]allow_double_quotes: bool | None = None+++@dataclass(frozen=True)+class SourceReferencingIntegration:+ id: UUID+ source_type: str+ prefix: str | None+ # The inputs did not decode, so the source may point at the row. The search counts it as a user.+ unreadable: bool = Falsediff --git a/products/warehouse_sources/backend/integration_usages.py b/products/warehouse_sources/backend/integration_usages.pynew file mode 100644index 000000000000..f1e695f80e70--- /dev/null+++ b/products/warehouse_sources/backend/integration_usages.py@@ -0,0 +1,25 @@+"""The warehouse sources that use an integration row. The integrations SDK loads this module."""++from posthog.integrations import IntegrationUsage++from products.warehouse_sources.backend.facade.contracts import (+ WAREHOUSE_SOURCE_USAGE_TYPE,+ SourceReferencingIntegration,+)+from products.warehouse_sources.backend.logic.integration_references import list_sources_using_integration+++def integration_usages(team_id: int, integration_id: int) -> list[IntegrationUsage]:+ return [+ IntegrationUsage(+ type=WAREHOUSE_SOURCE_USAGE_TYPE,+ id=str(source.id),+ name=_name(source),+ )+ for source in list_sources_using_integration(team_id=team_id, integration_pk=integration_id)+ ]+++def _name(source: SourceReferencingIntegration) -> str:+ name = f"{source.source_type} ({source.prefix})" if source.prefix else source.source_type+ return f"unreadable source: {name}" if source.unreadable else namediff --git a/products/warehouse_sources/backend/logic/credential_auth_types.py b/products/warehouse_sources/backend/logic/credential_auth_types.pynew file mode 100644index 000000000000..86b613feea3c--- /dev/null+++ b/products/warehouse_sources/backend/logic/credential_auth_types.py@@ -0,0 +1,40 @@+"""The `Integration` kind and auth type of the row that holds a source's typed-in credentials.++The kind comes from the generated `facade/credential_kinds.py`, and the auth type from the generated+`facade/credential_auth_types.py`. A source type has exactly one of each. On a catalogue kind with an+OAuth default, such as `stripe`, the typed-in row has a second auth type (`token`), so code that reads+the OAuth rows of the kind never gets a typed-in row.+"""++from posthog.integrations import AuthAccessor, AuthType, IntegrationManager++from products.warehouse_sources.backend.facade.credential_auth_types import CREDENTIAL_AUTH_TYPES+from products.warehouse_sources.backend.facade.credential_kinds import CREDENTIAL_KINDS+++class UnknownCredentialKindError(ValueError):+ """The source type has no credential kind, for example the Custom source."""+++def credential_kind(source_type: str) -> str:+ try:+ return CREDENTIAL_KINDS[str(source_type)]+ except KeyError:+ raise UnknownCredentialKindError(f"Source type {source_type!r} has no credential kind") from None+++def typed_in_auth_type(source_type: str) -> AuthType:+ """The auth type of the typed-in row of the source type.++ Raises ValueError for a source that has only OAuth fields, because such a source has no typed-in row.+ """+ auth_type = AuthType(CREDENTIAL_AUTH_TYPES[credential_kind(source_type)])+ if auth_type == AuthType.OAUTH:+ raise ValueError(f"Source type {source_type!r} has no typed-in credentials")+ return auth_type+++def credentials_accessor(source_type: str) -> AuthAccessor:+ """The SDK accessor of the typed-in rows of the source type: its kind, its auth type, marked rows only."""+ rows = IntegrationManager.source(credential_kind(source_type))+ return rows.token if typed_in_auth_type(source_type) == AuthType.TOKEN else rows.credentialsdiff --git a/products/warehouse_sources/backend/logic/integration_references.py b/products/warehouse_sources/backend/logic/integration_references.pynew file mode 100644index 000000000000..45af28b825bd--- /dev/null+++ b/products/warehouse_sources/backend/logic/integration_references.py@@ -0,0 +1,117 @@+"""Find the warehouse sources that point at a core ``Integration``.++A source points at its typed-in credentials row with its ``credentials_integration_id`` column, which+one indexed query reads. An OAuth source still stores its pointer as a ``*_integration_id`` field in its+inputs. The inputs are encrypted, so SQL cannot search them. That search loads the inputs of the+non-deleted sources of one team, which keeps the cost bounded by the size of that team.+"""++from collections.abc import Mapping+from typing import Any++from posthog.helpers.encrypted_fields import FERNET_TOKEN_PREFIX+from posthog.integrations import IntegrationManager, IntegrationNotFound, IntegrationReference++from products.warehouse_sources.backend.facade.contracts import SourceReferencingIntegration+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++POINTER_SUFFIX = "_integration_id"+# The name of the reference column. Inputs never hold the typed-in pointer, so the inputs search skips+# a stale key of this name.+_COLUMN_POINTER_KEY = "credentials_integration_id"+++def list_sources_using_integration(team_id: int, integration_pk: int) -> list[SourceReferencingIntegration]:+ users = {source.id: source for source in _sources_by_column(team_id, integration_pk)}+ for source in _sources_by_inputs(team_id, integration_pk):+ users.setdefault(source.id, source)+ return list(users.values())+++def _sources_by_column(team_id: int, integration_pk: int) -> list[SourceReferencingIntegration]:+ sources = (+ ExternalDataSource.objects.select_related(None)+ .filter(+ team_id=team_id,+ credentials_integration_id=str(IntegrationReference.from_legacy_id(integration_pk)),+ )+ .exclude(deleted=True)+ .only("id", "source_type", "prefix")+ )+ return [+ SourceReferencingIntegration(id=source.id, source_type=str(source.source_type), prefix=source.prefix)+ for source in sources+ ]+++def _sources_by_inputs(team_id: int, integration_pk: int) -> list[SourceReferencingIntegration]:+ sources = list(+ ExternalDataSource.objects.select_related(None)+ .filter(team_id=team_id)+ .exclude(deleted=True)+ .only("id", "source_type", "prefix", "job_inputs")+ )+ inputs_by_source = {+ source_id: inputs+ for source_id, inputs in SourceInputsStore.load_many(sources).items()+ if not _has_ciphertext(inputs)+ }+ wanted = str(integration_pk)+ users = [+ SourceReferencingIntegration(id=source.id, source_type=str(source.source_type), prefix=source.prefix)+ for source in sources+ if source.id in inputs_by_source and _has_pointer(inputs_by_source[source.id], wanted)+ ]+ # A source whose inputs do not decode may hold an OAuth pointer to the row. When it can use the kind+ # of the row, it counts as a user, so a shared edit asks for a confirmation and a delete is refused.+ unreadable = [source for source in sources if source.id not in inputs_by_source]+ kind = _oauth_row_kind(team_id, integration_pk) if unreadable else None+ users += [+ SourceReferencingIntegration(+ id=source.id, source_type=str(source.source_type), prefix=source.prefix, unreadable=True+ )+ for source in unreadable+ if kind is not None and _can_use_kind(str(source.source_type), kind)+ ]+ return users+++def _oauth_row_kind(team_id: int, integration_pk: int) -> str | None:+ # Inputs point only at rows that are not typed-in source rows, and `IntegrationManager.any` skips+ # typed-in rows. So an unreadable source never counts as a user of a typed-in row.+ try:+ return IntegrationManager.any.get(team_id, integration_pk).kind+ except IntegrationNotFound:+ return None+++def _can_use_kind(source_type: str, kind: 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)).credential_kind == kind+ except ValueError:+ return True+++def _has_pointer(inputs: Mapping[str, Any], wanted: str) -> bool:+ for key, value in inputs.items():+ if key.endswith(POINTER_SUFFIX) and key != _COLUMN_POINTER_KEY and value is not None and str(value) == wanted:+ return True+ # Switch groups and select options nest their fields one level down.+ if isinstance(value, Mapping) and _has_pointer(value, wanted):+ return True+ return False+++def _has_ciphertext(value: Any) -> bool:+ if isinstance(value, Mapping):+ return any(_has_ciphertext(item) for item in value.values())+ if isinstance(value, list):+ return any(_has_ciphertext(item) for item in value)+ return isinstance(value, str) and value.startswith(FERNET_TOKEN_PREFIX)diff --git a/products/warehouse_sources/backend/logic/source_credentials.py b/products/warehouse_sources/backend/logic/source_credentials.pynew file mode 100644index 000000000000..9567e0226638--- /dev/null+++ b/products/warehouse_sources/backend/logic/source_credentials.py@@ -0,0 +1,387 @@+"""The only code that reads or writes the `Integration` rows that hold warehouse sources' typed-in credentials.++A row has the kind of the credential provider (`postgresql`, `stripe`, `ab-tasty`) and the auth type+that the typed-in fields have (`token` or `credentials`). See `credential_auth_types.py`. The row holds+the connection fields under `sensitive_config["fields"]`, and `config` holds the+`warehouse_source_type` marker. A source points at its row with its `credentials_integration_id`+column, in the string form of `IntegrationReference`. An OAuth source keeps its own `*_integration_id`+key in its inputs and has no row here.++Every read and write goes through `IntegrationManager.source(kind)` of the integrations SDK, which sees+only marked rows of the kind and auth type.++Several sources (and later other products) can use one row. An edit of a shared row needs a+confirmation, and an edit that changes where the credentials connect makes a new row. The store+never deletes a row: a row that nothing uses stays in the integrations list.++No method returns a queryset or a model, so a later credentials service can sit behind the same+methods without a change to the callers.+"""++import json+from collections.abc import Iterable, Mapping+from typing import Any+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+from posthog.integrations import AuthAccessor, IntegrationNotFound, IntegrationReference, IntegrationUsage+from posthog.models.integration import WAREHOUSE_SOURCE_TYPE_CONFIG_KEY+from posthog.sync import database_sync_to_async_pool++from products.warehouse_sources.backend.facade.contracts import WAREHOUSE_SOURCE_USAGE_TYPE, SharedCredentialsError+from products.warehouse_sources.backend.logic.credential_auth_types import credentials_accessor+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+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)+++class CredentialsUnreadableError(ValueError):+ """A row exists but its `sensitive_config` does not hold readable fields. The cause is usually a+ decryption failure. The message never holds a value, because values are credentials."""+++class CredentialsNotFoundError(LookupError):+ """The reference does not point at a credentials row of the source's team and kind."""+++@frozen+class CredentialsUnreadable:+ """In a `get_many` result: the row exists, but it cannot be read."""+++class WarehouseSourceCredentialsStore:+ @staticmethod+ def get(source: ExternalDataSource) -> dict[str, Any] | None:+ """The connection fields in the row that the source points at, or None when there is no such row.++ Raises `CredentialsUnreadableError` when the row exists but cannot be read. Callers must not+ treat that as "no fields".+ """+ pk = _pk(source)+ rows = _accessor_or_none(source)+ if pk is None or rows is None:+ return None+ try:+ row = rows.get(source.team_id, pk)+ except IntegrationNotFound:+ return None+ fields = _fields_of(row.sensitive_config)+ if fields is None:+ raise CredentialsUnreadableError(f"Credentials of source {source.id} are unreadable")+ return fields++ @staticmethod+ def get_many(sources: Iterable[ExternalDataSource]) -> dict[UUID, dict[str, Any] | CredentialsUnreadable]:+ """`get` for each source, keyed by source id, with one query per team and source type.++ A source without a row is left out. A source whose row cannot be read maps to+ `CredentialsUnreadable`, so one bad row does not fail a whole list.+ """+ groups: dict[tuple[int, str], list[tuple[ExternalDataSource, int]]] = {}+ for source in sources:+ pk = _pk(source)+ if pk is not None:+ groups.setdefault((source.team_id, str(source.source_type)), []).append((source, pk))++ result: dict[UUID, dict[str, Any] | CredentialsUnreadable] = {}+ for (team_id, _source_type), group in groups.items():+ rows = _accessor_or_none(group[0][0])+ if rows is None:+ continue+ found = rows.get_many(team_id, {pk for _, pk in group})+ for source, pk in group:+ row = found.get(pk)+ if row is None:+ continue+ fields = _fields_of(row.sensitive_config)+ result[source.id] = fields if fields is not None else CredentialsUnreadable()+ return result++ @staticmethod+ def create(source: ExternalDataSource, fields: Mapping[str, Any]) -> IntegrationReference:+ """Create a row with the connection fields of the source, and point the source at it.++ The source is not saved. The caller saves it with its inputs (`SourceInputsStore.save` or+ `create`, or a full model save), so the source never points at a row that its inputs do not use.++ Raises ValueError for a source without typed-in credentials (an OAuth-only source, or Custom).+ """+ source_type = str(source.source_type)+ row = credentials_accessor(source_type).create(+ source.team_id,+ # Opaque, so a typed-in row never takes the natural key of a row that other code writes.+ external_id=uuid4().hex,+ config={+ WAREHOUSE_SOURCE_TYPE_CONFIG_KEY: source_type,+ "display_name": f"{source_type} ({source.prefix})" if source.prefix else source_type,+ },+ sensitive_config={"fields": dict(fields)},+ created_by_id=source.created_by_id,+ )+ return _point_at(source, row.id)++ @staticmethod+ def update(+ source: ExternalDataSource, fields: Mapping[str, Any], *, allow_shared: bool = False+ ) -> IntegrationReference:+ """Write the connection fields to the row that the source points at. Returns the reference of+ the row that now holds them: the same row, or a new row.++ When other sources or products also use the row, a change to an identifying field (host,+ account) makes a new row, so the other users keep their connection. The source then points at+ the new row, and the caller saves it as for `create`. A change to the other fields (a secret+ rotation) raises `SharedCredentialsError` with the other users, unless `allow_shared` confirms+ it. Raises `CredentialsNotFoundError` when there is no row.+ """+ pk = _pk(source)+ if pk is None:+ raise CredentialsNotFoundError(f"Source {source.id} has no credentials reference")+ source_type = str(source.source_type)+ rows = credentials_accessor(source_type)+ try:+ row = rows.get(source.team_id, pk)+ others = _other_usages(rows, source, row.id)+ except IntegrationNotFound as error:+ raise CredentialsNotFoundError(f"Credentials of source {source.id} do not exist") from error+ if others:+ current = _fields_of(row.sensitive_config)+ if current is None or _identity(source_type, current) != _identity(source_type, fields):+ return WarehouseSourceCredentialsStore.create(source, fields)+ if not allow_shared:+ raise SharedCredentialsError(row.id, others)+ # No lock spans the usages check and the write. When two sources edit one shared row at the+ # same time, the last write wins. The source lock serializes the edits of one source only.+ try:+ rows.update(source.team_id, pk, sensitive_config_patch={"fields": dict(fields)})+ except IntegrationNotFound as error:+ raise CredentialsNotFoundError(f"Credentials of source {source.id} do not exist") from error+ return IntegrationReference.from_legacy_id(pk)++ @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+ async def aget(source: ExternalDataSource) -> dict[str, Any] | None:+ return await database_sync_to_async_pool(WarehouseSourceCredentialsStore.get)(source)++ @staticmethod+ async def acreate(source: ExternalDataSource, fields: Mapping[str, Any]) -> IntegrationReference:+ return await database_sync_to_async_pool(WarehouseSourceCredentialsStore.create)(source, fields)++ @staticmethod+ async def aupdate(+ source: ExternalDataSource, fields: Mapping[str, Any], *, allow_shared: bool = False+ ) -> IntegrationReference:+ def _update() -> IntegrationReference:+ return WarehouseSourceCredentialsStore.update(source, fields, allow_shared=allow_shared)++ return await database_sync_to_async_pool(_update)()+++def _accessor_or_none(source: ExternalDataSource) -> AuthAccessor | None:+ # A source without typed-in credentials (OAuth-only, Custom) has no row to read.+ try:+ return credentials_accessor(str(source.source_type))+ except ValueError:+ return None+++def _point_at(source: ExternalDataSource, pk: int) -> IntegrationReference:+ reference = IntegrationReference.from_legacy_id(pk)+ source.credentials_integration_id = str(reference)+ return reference+++def _pk(source: ExternalDataSource) -> int | None:+ """The legacy id in the reference column, or None when the source points at no row the SDK can read."""+ stored = source.credentials_integration_id+ if stored is None:+ return None+ try:+ reference = IntegrationReference.parse(stored)+ except ValueError:+ # Only the store writes the column, so this is a bad write. The source then has no row: a read+ # finds no credentials and an update raises, and neither reads a row of another source.+ logger.warning("warehouse_source_credentials_reference_invalid", team_id=source.team_id, source_id=source.id)+ return None+ # A UUID points at a row in the credentials service, which the SDK cannot read yet.+ return reference.legacy_id+++def _other_usages(rows: AuthAccessor, source: ExternalDataSource, pk: int) -> list[IntegrationUsage]:+ """The usages of the row other than this source. Raises `IntegrationNotFound` when the row is not in scope."""+ return [+ usage+ for usage in rows.usages(source.team_id, pk)+ if not (usage.type == WAREHOUSE_SOURCE_USAGE_TYPE and usage.id == str(source.id))+ ]+++def _identity(source_type: str, fields: Mapping[str, Any]) -> str:+ # 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,+ )++ source = SourceRegistry.get_source(ExternalDataSourceType(source_type))+ return json.dumps(_identity_parts(fields, source.credential_identity_fields), sort_keys=True)+++def _identity_parts(fields: Mapping[str, Any], names: frozenset[str], prefix: str = "") -> dict[str, Any]:+ # A source can declare an identity field inside a select option (Snowflake keeps `user` under+ # `auth_type`), so look at every depth. The path keeps two fields of one name apart.+ parts: dict[str, Any] = {}+ for key, value in fields.items():+ path = f"{prefix}{key}"+ if key in names:+ part = _identity_value(str(key), value)+ # An unset and a blank value match.+ if part not in ("", {}):+ parts[path] = part+ elif isinstance(value, Mapping):+ parts.update(_identity_parts(value, names, f"{path}."))+ return parts+++def _identity_value(key: str, value: Any) -> Any:+ # These two fields also hold secrets. A secret change is a rotation, not a new connection, so+ # compare only the parts that say where the credentials connect and as which account.+ if key == "ssh_tunnel" and isinstance(value, Mapping):+ auth = value.get("auth_type")+ return {+ part: item+ for part, item in {+ "enabled": _normalized(value.get("enabled")).lower(),+ "host": _normalized(value.get("host")),+ "port": _normalized(value.get("port")),+ "username": _normalized(auth.get("username") if isinstance(auth, Mapping) else None),+ }.items()+ if item+ }+ if key == "connection_string" and isinstance(value, str):+ return _connection_string_identity(value)+ return _normalized(value)+++# Keys of a `key=value;...` connection string (ADO.NET, libpq) that say where it connects and as whom.+_CONNECTION_STRING_IDENTITY_KEYS = frozenset(+ {+ "server",+ "host",+ "hostaddr",+ "address",+ "addr",+ "data source",+ "port",+ "user",+ "user id",+ "uid",+ "username",+ "database",+ "dbname",+ "initial catalog",+ "account",+ }+)+++def _connection_string_identity(value: str) -> Any:+ value = value.strip()+ if not value:+ return ""+ if "://" in value:+ uri = urlsplit(value)+ userinfo, _, hosts = uri.netloc.rpartition("@")+ identity = {+ "scheme": uri.scheme.lower(),+ "user": unquote(userinfo.partition(":")[0]),+ "hosts": hosts.lower(),+ "database": uri.path.removeprefix("/"),+ }+ if uri.scheme.lower() in ("mongodb", "mongodb+srv"):+ options = {key.lower(): item for key, item in parse_qsl(uri.query)}+ identity["auth_source"] = options.get("authsource", unquote(uri.path.removeprefix("/")) or "admin")+ return identity+ # ADO.NET separates pairs with ";" and has keys with spaces ("User Id"). libpq separates with spaces.+ pairs = [pair.partition("=") for pair in (value.split(";") if ";" in value else value.split()) if "=" in pair]+ parts = {+ key.strip().lower(): item.strip()+ for key, _, item in pairs+ if key.strip().lower() in _CONNECTION_STRING_IDENTITY_KEYS+ }+ # A format this does not know compares whole, so a change can only make a new row.+ return parts or value+++def _normalized(value: Any) -> Any:+ # Encrypted fields store leaves as strings, so compare strings. An unset and a blank value match.+ if isinstance(value, Mapping):+ return {str(key): _normalized(item) for key, item in value.items()}+ if isinstance(value, list):+ return [_normalized(item) for item in value]+ return "" if value is None else str(value)+++def _fields_of(sensitive_config: Any) -> dict[str, Any] | None:+ # `sensitive_config` ignores decrypt errors and then reads back as {}. A readable row always has a+ # "fields" mapping, even when the source has no connection fields.+ if not isinstance(sensitive_config, Mapping):+ return None+ fields = sensitive_config.get("fields")+ if not isinstance(fields, Mapping):+ return 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.+ try:+ return _recover_leaves(dict(fields))+ except _UndecryptableLeaf:+ return None+++class _UndecryptableLeaf(Exception):+ pass+++def _recover_leaves(value: Any) -> Any:+ if isinstance(value, dict):+ return {key: _recover_leaves(item) for key, item in value.items()}+ if isinstance(value, list):+ return [_recover_leaves(item) for item in value]+ if isinstance(value, str) and value.startswith(FERNET_TOKEN_PREFIX):+ recovered = _SENSITIVE_CONFIG_FIELD.decrypt_all_layers(value)+ if recovered is None:+ raise _UndecryptableLeaf+ return recovered+ return valuediff --git a/products/warehouse_sources/backend/logic/source_inputs.py b/products/warehouse_sources/backend/logic/source_inputs.pyindex 67d4c0857196..ed1639fa27a1 100644--- a/products/warehouse_sources/backend/logic/source_inputs.py+++ b/products/warehouse_sources/backend/logic/source_inputs.py@@ -90,9 +90,13 @@ class SourceInputsStore:*,extra_update_fields: Sequence[str] = DEFAULT_EXTRA_UPDATE_FIELDS,) -> None:- """Replace all inputs of the source and save them."""+ """Replace all inputs of the source and save them.++ The same write saves `credentials_integration_id`, which `WarehouseSourceCredentialsStore`+ sets on the source. So the source points at its credentials row only together with its inputs.+ """SourceInputsStore.assign(source, inputs)- source.save(update_fields=["job_inputs", *extra_update_fields])+ source.save(update_fields=["job_inputs", "credentials_integration_id", *extra_update_fields])@staticmethoddef create(*, inputs: Mapping[str, Any], **fields: Any) -> ExternalDataSource:@@ -123,7 +127,10 @@ class SourceInputsStore:inputs.update(updates)for key in remove:inputs.pop(key, None)- SourceInputsStore.save(source, inputs, extra_update_fields=extra_update_fields)+ SourceInputsStore.assign(source, inputs)+ # A runtime write never changes the credentials, so it leaves the reference column alone. A sync+ # holds its source for a long time, and its copy of the column can be older than the row.+ source.save(update_fields=["job_inputs", *extra_update_fields])return inputs@staticmethoddiff --git a/products/warehouse_sources/backend/migrations/0193_externaldatasource_credentials_integration_id.py b/products/warehouse_sources/backend/migrations/0193_externaldatasource_credentials_integration_id.pynew file mode 100644index 000000000000..22defc47500a--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0193_externaldatasource_credentials_integration_id.py@@ -0,0 +1,15 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("warehouse_sources", "0192_repin_loop_returns_api_version"),+ ]++ operations = [+ migrations.AddField(+ model_name="externaldatasource",+ name="credentials_integration_id",+ field=models.CharField(blank=True, max_length=64, null=True),+ ),+ ]diff --git a/products/warehouse_sources/backend/migrations/0194_externaldatasource_credentials_integration_idx.py b/products/warehouse_sources/backend/migrations/0194_externaldatasource_credentials_integration_idx.pynew file mode 100644index 000000000000..aa22783418bb--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0194_externaldatasource_credentials_integration_idx.py@@ -0,0 +1,22 @@+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("warehouse_sources", "0193_externaldatasource_credentials_integration_id"),+ ]++ operations = [+ SafeAddIndexConcurrently(+ model_name="externaldatasource",+ index=models.Index(+ condition=models.Q(credentials_integration_id__isnull=False),+ fields=["team", "credentials_integration_id"],+ name="eds_team_credentials_int_idx",+ ),+ ),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex 3d559ac5e2b2..e8f52c13c054 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0192_repin_loop_returns_api_version+0194_externaldatasource_credentials_integration_idxdiff --git a/products/warehouse_sources/backend/models/external_data_source.py b/products/warehouse_sources/backend/models/external_data_source.pyindex 0507d6d6b3f8..68b018c9c843 100644--- a/products/warehouse_sources/backend/models/external_data_source.py+++ b/products/warehouse_sources/backend/models/external_data_source.py@@ -5,7 +5,9 @@ from django.db import models, transactionfrom django.utils import timezoneimport structlog+from prometheus_client import Counter+from posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.encrypted_fields import EncryptedJSONFieldfrom posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.utils import CreatedMetaFields, DeletedMetaFields, UpdatedMetaFields, UUIDTModel, sane_repr@@ -24,6 +26,11 @@ 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"@@ -64,6 +71,9 @@ class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField# encrypted at rest.api_version = models.CharField(max_length=128, null=True, blank=True)job_inputs = EncryptedJSONField(null=True, blank=True)+ # The integration row with the source's credentials: a legacy int id or a UUID, in the string form of+ # `IntegrationReference`. No foreign key, because the rows move to a separate credentials service.+ credentials_integration_id = models.CharField(max_length=64, null=True, blank=True)connection_metadata = models.JSONField(default=dict, blank=True, null=True)are_tables_created = models.BooleanField(default=False)prefix = models.CharField(max_length=100, null=True, blank=True)@@ -92,6 +102,13 @@ class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldclass Meta:db_table = "posthog_externaldatasource"+ indexes = [+ models.Index(+ fields=["team", "credentials_integration_id"],+ name="eds_team_credentials_int_idx",+ condition=models.Q(credentials_integration_id__isnull=False),+ ),+ ]def merge_connection_metadata(self, metadata: dict[str, Any]) -> None:"""Merge ``metadata`` into ``connection_metadata`` under a lock on this row.@@ -340,6 +357,24 @@ class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldsource = SourceRegistry.get_source(ExternalDataSourceType(self.source_type))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/presentation/views/external_data_source/shared_credentials.py b/products/warehouse_sources/backend/presentation/views/external_data_source/shared_credentials.pynew file mode 100644index 000000000000..26437a4883dc--- /dev/null+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/shared_credentials.py@@ -0,0 +1,31 @@+"""The API response when a source edit would change credentials that other objects also use."""++from rest_framework import status+from rest_framework.response import Response++from products.warehouse_sources.backend.facade.contracts import UPDATE_SHARED_CREDENTIALS_PARAM, SharedCredentialsError++SHARED_CREDENTIALS_CODE = "shared_credentials"+++def shared_credentials_conflict_response(error: SharedCredentialsError) -> Response:+ """A 409 that names the other users of the credentials, so the client can ask for a confirmation.++ The client sends the edit again with `update_shared_credentials=true` to change the credentials+ for every user.+ """+ names = ", ".join(usage.name for usage in error.usages)+ return Response(+ {+ "detail": (+ f"These credentials are also used by {names}. "+ f"Send {UPDATE_SHARED_CREDENTIALS_PARAM}=true to change them everywhere."+ ),+ "type": "conflict",+ "code": SHARED_CREDENTIALS_CODE,+ "attr": None,+ "integration_id": error.integration_id,+ "usages": [{"type": str(usage.type), "id": usage.id, "name": usage.name} for usage in error.usages],+ },+ status=status.HTTP_409_CONFLICT,+ )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.pyindex f56da6fea593..0fa2adf82384 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@@ -2,7 +2,7 @@ import datetimeimport functoolsimport dataclassesfrom abc import ABC, abstractmethod-from collections.abc import Callable, Iterable, Mapping+from collections.abc import Callable, Iterable, Iterator, Mappingfrom typing import TYPE_CHECKING, Any, Generic, Optional, TypeVar, Union, castimport structlog@@ -20,6 +20,7 @@ if TYPE_CHECKING:from products.warehouse_sources.backend.facade.source_config import (SourceConfig,+ SourceFieldConfig,SourceFieldCredentialAccountSelectConfig,SourceFieldFileUploadConfig,SourceFieldInputConfig,@@ -106,6 +107,35 @@ FieldType = Union[SourceCredentialsValidationResult = tuple[bool, str | None]+# Field names that say where stored credentials connect, and as which account, for any source that+# declares them. The input of the default `credential_identity_fields`.+GENERIC_IDENTITY_FIELDS: frozenset[str] = frozenset(+ {+ "host",+ "port",+ "instance_url",+ "connection_string",+ "ssh_tunnel",+ "user",+ "username",+ "account",+ "account_id",+ "account_sid",+ }+)+++def _declared_field_names(fields: Iterable[SourceFieldConfig]) -> Iterator[str]:+ """The names of the form fields at any depth: in switch groups and in the options of a select."""+ for field in fields:+ yield field.name+ if isinstance(field, SourceFieldSwitchGroupConfig):+ yield from _declared_field_names(field.fields)+ elif isinstance(field, SourceFieldSelectConfig):+ for option in field.options:+ yield from _declared_field_names(option.fields or [])++# Label used by sources whose vendor has no meaningful API versioning. Version strings are# opaque vendor labels (Stripe date versions, semver, names) — never parsed or ordered.UNVERSIONED_API_VERSION = "v1"@@ -521,6 +551,18 @@ class _BaseSource(ABC, Generic[ConfigType]):a differently named field (e.g. Okta's ``okta_domain``) should list it here."""return []+ @property+ def credential_identity_fields(self) -> frozenset[str]:+ """Connection fields that say where the stored credentials connect, and as which account.++ When other sources or products share the credentials row, a change to one of these fields makes a+ new row, so the other users keep their connection. The default is ``connection_host_fields`` plus+ each name in ``GENERIC_IDENTITY_FIELDS`` that the source declares as a form field (at any depth) or+ stores as a config attribute."""+ declared = set(_declared_field_names(self.get_source_config.fields))+ declared |= {config_field.name for config_field in dataclasses.fields(self._config_class)}+ return frozenset(self.connection_host_fields) | (GENERIC_IDENTITY_FIELDS & declared)+@propertydef 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/tests/test_migration_repin_langfuse_api_version_v3.py b/products/warehouse_sources/backend/tests/test_migration_repin_langfuse_api_version_v3.pydeleted file mode 100644index 56fd168b3b80..000000000000--- a/products/warehouse_sources/backend/tests/test_migration_repin_langfuse_api_version_v3.py+++ /dev/null@@ -1,52 +0,0 @@-from typing import Any--from posthog.test.base import TestMigrations---class TestRepinLangfuseApiVersionV3(TestMigrations):- migrate_from = "0183_repin_gusto_api_version"- migrate_to = "0184_repin_langfuse_api_version_v3"-- def setUpBeforeMigration(self, apps: Any) -> None:- ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")- ExternalDataSchema = apps.get_model("warehouse_sources", "ExternalDataSchema")-- def source(source_type: str, api_version: str | None, schemas: list[tuple[str, bool, bool | None]]) -> str:- created = ExternalDataSource.objects.create(- team_id=self.team.id,- source_id="source-id",- connection_id="connection-id",- status="Completed",- source_type=source_type,- api_version=api_version,- )- for name, should_sync, deleted in schemas:- ExternalDataSchema.objects.create(- team_id=self.team.id,- source=created,- name=name,- should_sync=should_sync,- deleted=deleted,- api_version="v1" if name == "scores" else None,- )- return str(created.id)-- self.expected = {- source("Langfuse", "v1", [("observations", True, False), ("traces", False, False)]): "v3",- source("Langfuse", "v2", [("scores", True, False), ("sessions", True, True)]): "v3",- source("Langfuse", "v2", [("observations", True, False), ("traces", True, False)]): "v2",- source("Langfuse", "v1", [("sessions", True, False)]): "v1",- source("Langfuse", "v1", [("traces", True, None)]): "v1",- source("Langfuse", None, [("traces", False, False)]): None,- source("Langfuse", "v3", []): "v3",- source("Ably", "v1", []): "v1",- }-- def test_repins_only_sources_that_lose_no_synced_table(self) -> None:- assert self.apps is not None- ExternalDataSource = self.apps.get_model("warehouse_sources", "ExternalDataSource")- ExternalDataSchema = self.apps.get_model("warehouse_sources", "ExternalDataSchema")-- pins = dict(ExternalDataSource.objects.filter(id__in=self.expected).values_list("id", "api_version"))- assert {str(source_id): pin for source_id, pin in pins.items()} == self.expected- assert ExternalDataSchema.objects.get(name="scores").api_version == "v1"diff --git a/products/warehouse_sources/backend/tests/test_migration_repin_lovable_api_version_2026_09_11.py b/products/warehouse_sources/backend/tests/test_migration_repin_lovable_api_version_2026_09_11.pyindex dc984cab3c89..1656cec12eb2 100644--- a/products/warehouse_sources/backend/tests/test_migration_repin_lovable_api_version_2026_09_11.py+++ b/products/warehouse_sources/backend/tests/test_migration_repin_lovable_api_version_2026_09_11.py@@ -1,9 +1,9 @@from typing import Any-from posthog.test.base import TestMigrations+from posthog.test.base import NonAtomicTestMigrations-class TestRepinLovableApiVersion20260911(TestMigrations):+class TestRepinLovableApiVersion20260911(NonAtomicTestMigrations):migrate_from = "0188_reset_trunkio_v2_failing_tests"migrate_to = "0189_repin_lovable_api_version_2026_09_11"diff --git a/products/warehouse_sources/backend/tests/test_source_credentials.py b/products/warehouse_sources/backend/tests/test_source_credentials.pynew file mode 100644index 000000000000..340188f02b1e--- /dev/null+++ b/products/warehouse_sources/backend/tests/test_source_credentials.py@@ -0,0 +1,845 @@+import csv+from typing import Any, cast+from uuid import uuid4++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.test import SimpleTestCase++from cryptography.fernet import Fernet+from parameterized import parameterized++from posthog.helpers.encrypted_fields import EncryptedJSONField+from posthog.integrations import AuthType, IntegrationInUse, IntegrationManager, IntegrationRecord, IntegrationUsage+from posthog.models.integration import WAREHOUSE_SOURCE_TYPE_CONFIG_KEY, AuthTypeSelector, Integration+from posthog.models.integration.auth_types import catalogued_kinds, kind_auth_types+from posthog.models.integration.model import integration_kind_choices+from posthog.models.team import Team++from products.warehouse_sources.backend.facade.contracts import SharedCredentialsError+from products.warehouse_sources.backend.facade.credential_kinds import CREDENTIAL_KINDS+from products.warehouse_sources.backend.logic.credential_auth_types import (+ UnknownCredentialKindError,+ typed_in_auth_type,+)+from products.warehouse_sources.backend.logic.integration_references import list_sources_using_integration+from products.warehouse_sources.backend.logic.source_credentials import (+ CredentialsNotFoundError,+ CredentialsUnreadable,+ CredentialsUnreadableError,+ 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.presentation.views.external_data_source.shared_credentials import (+ shared_credentials_conflict_response,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.job_input_classification import (+ CLASSIFICATION_AUDIT_PATH,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.types import ExternalDataSourceType+from products.workflows.backend.facade.contracts import WorkflowSummary++PG_FIELDS: dict[str, Any] = {+ "host": "db.example.com",+ "port": "5432",+ "user": "reader",+ "password": "fake-password",+ "ssh_tunnel": {"enabled": "True"},+}++STRIPE_FIELDS: dict[str, Any] = {"auth_method": {"selection": "api_key", "stripe_secret_key": "fake-key"}}++SNOWFLAKE_FIELDS: dict[str, Any] = {+ "account_id": "acct-1",+ "database": "analytics",+ "auth_type": {"selection": "password", "user": "reader", "password": "fake-password"},+}+PG_URL_FIELDS: dict[str, Any] = {+ "connection_string": "postgresql://reader:[email protected]:5432/app?sslmode=require"+}+MSSQL_ADO_FIELDS: dict[str, Any] = {+ "connection_string": "Server=db.example.com,1433;User Id=reader;Password=fake-password;Database=app"+}+PG_TUNNEL_FIELDS: dict[str, Any] = {+ **PG_FIELDS,+ "ssh_tunnel": {+ "enabled": "True",+ "host": "bastion.example.com",+ "port": "22",+ "auth_type": {"selection": "keypair", "username": "tunnel", "private_key": "fake-key", "passphrase": "fake"},+ },+}+++def _with(fields: dict[str, Any], path: str, value: Any) -> dict[str, Any]:+ head, _, rest = path.partition(".")+ return {**fields, head: _with(fields[head], rest, value) if rest else value}+++def _row(pk: int) -> Integration:+ return Integration.objects._with_auth(AuthTypeSelector.ANY).get(id=pk)+++class TestWarehouseSourceCredentialsStore(BaseTest):+ def _source(+ self, source_type: ExternalDataSourceType = ExternalDataSourceType.POSTGRES, team: Team | 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={"schema": "public"},+ created_by=self.user,+ )++ def _create(self, source: ExternalDataSource, fields: dict[str, Any]) -> int:+ reference = WarehouseSourceCredentialsStore.create(source, fields)+ SourceInputsStore.save(source, SourceInputsStore.load(source))+ assert reference.legacy_id is not None+ return reference.legacy_id++ def _referencing(self, pk: int, source_type: ExternalDataSourceType = ExternalDataSourceType.POSTGRES) -> None:+ source = self._source(source_type)+ source.credentials_integration_id = str(pk)+ source.save()++ def _fields_of_row(+ self, pk: int, source_type: ExternalDataSourceType = ExternalDataSourceType.POSTGRES+ ) -> dict[str, Any] | None:+ reader = ExternalDataSource(team=self.team, source_type=source_type, credentials_integration_id=str(pk))+ return WarehouseSourceCredentialsStore.get(reader)++ @parameterized.expand(+ [+ ("postgres_default_auth", ExternalDataSourceType.POSTGRES, PG_FIELDS, "postgresql", "credentials", False),+ ("stripe_token_on_oauth_kind", ExternalDataSourceType.STRIPE, STRIPE_FIELDS, "stripe", "token", True),+ (+ "github_token_on_oauth_kind",+ ExternalDataSourceType.GITHUB,+ {"auth_method": {"selection": "pat", "personal_access_token": "fake-token"}},+ "github",+ "token",+ True,+ ),+ (+ "twilio_credentials_on_token_kind",+ ExternalDataSourceType.TWILIO,+ {"account_sid": "AC1", "auth_method": {"selection": "api_key", "api_key_secret": "fake"}},+ "twilio",+ "credentials",+ True,+ ),+ (+ "databricks_default_auth",+ ExternalDataSourceType.DATABRICKS,+ {"host": "dbc.example.com", "auth_type": {"access_token": "fake"}},+ "databricks",+ "credentials",+ False,+ ),+ ("generated_token_kind", ExternalDataSourceType.ABLY, {"api_key": "fake-key"}, "ably", "token", False),+ ]+ )+ def test_create_writes_a_marked_row_of_the_provider_kind_and_auth_type(+ self,+ _name: str,+ source_type: ExternalDataSourceType,+ fields: dict[str, Any],+ kind: str,+ auth_type: str,+ stores_auth_type: bool,+ ) -> None:+ source = self._source(source_type)++ reference = WarehouseSourceCredentialsStore.create(source, fields)++ assert reference.legacy_id is not None and reference.uuid is None+ assert source.credentials_integration_id == str(reference.legacy_id)+ row = IntegrationManager.source(kind).any.get(self.team.id, reference.legacy_id)+ assert (row.team_id, row.kind, row.auth_type, row.created_by_id) == (+ self.team.id,+ kind,+ auth_type,+ self.user.id,+ )+ assert row.config[WAREHOUSE_SOURCE_TYPE_CONFIG_KEY] == source_type.value+ assert ("auth_type" in row.config) == stores_auth_type+ assert "fake" not in str(row.config)+ assert row.integration_id and row.integration_id != str(source.id)+ assert WarehouseSourceCredentialsStore.get(source) == fields+ assert "credentials_integration_id" not in SourceInputsStore.load(source)++ @parameterized.expand(+ [+ ("inputs_save", lambda source: SourceInputsStore.save(source, {"schema": "other"}), True),+ ("model_save", lambda source: source.save(), True),+ # A sync holds an old copy of its source, so a runtime write must not move the pointer.+ ("runtime_write", lambda source: SourceInputsStore.update_runtime(source, {"cdc_slot_name": "s"}), False),+ ("no_save", lambda source: None, False),+ ]+ )+ def test_the_pointer_reaches_the_database_only_with_a_save_of_the_inputs(+ self, _name: str, write: Any, saved: bool+ ) -> None:+ source = self._source()++ reference = WarehouseSourceCredentialsStore.create(source, PG_FIELDS)+ write(source)++ stored = ExternalDataSource.objects.get(id=source.id).credentials_integration_id+ assert stored == (str(reference) if saved else None)++ @parameterized.expand(+ [+ ("clickup", ExternalDataSourceType.CLICKUP, "clickup"),+ ("gitlab", ExternalDataSourceType.GITLAB, "gitlab"),+ ("google_calendar", ExternalDataSourceType.GOOGLECALENDAR, "google-calendar"),+ ("jira", ExternalDataSourceType.JIRA, "jira"),+ ("pardot", ExternalDataSourceType.PARDOT, "pardot"),+ ("twilio", ExternalDataSourceType.TWILIO, "twilio"),+ ("vercel", ExternalDataSourceType.VERCEL, "vercel"),+ ]+ )+ def test_catalogue_kind_accepts_the_derived_auth_type_of_its_source(+ self, _name: str, source_type: ExternalDataSourceType, kind: str+ ) -> None:+ assert typed_in_auth_type(source_type.value) == AuthType.CREDENTIALS+ assert AuthType.CREDENTIALS in kind_auth_types(kind).supported++ pk = self._create(self._source(source_type), {"api_key": "fake-key"})++ assert (_row(pk).kind, _row(pk).auth_type) == (kind, "credentials")++ @parameterized.expand(+ [+ # A typed-in row on a kind with an OAuth default is invisible to code that did not ask for it.+ ("stripe_token", ExternalDataSourceType.STRIPE, STRIPE_FIELDS, "stripe", False),+ ("github_token", ExternalDataSourceType.GITHUB, {"auth_method": {"selection": "pat"}}, "github", False),+ # A row with the default auth type of its kind: the unqualified manager skips it for its marker.+ ("postgres_credentials", ExternalDataSourceType.POSTGRES, PG_FIELDS, "postgresql", False),+ ]+ )+ def test_named_accessors_skip_source_rows(+ self,+ _name: str,+ source_type: ExternalDataSourceType,+ fields: dict[str, Any],+ kind: str,+ visible_unqualified: bool,+ ) -> None:+ pk = self._create(self._source(source_type), fields)++ assert Integration.objects.filter(id=pk).exists() == visible_unqualified+ assert IntegrationManager.kinds(kind).get_many(self.team.id, [pk]) == {}+ assert list(IntegrationManager.source(kind).any.get_many(self.team.id, [pk])) == [pk]+ assert list(IntegrationManager.any.with_source_rows().get_many(self.team.id, [pk])) == [pk]++ @parameterized.expand(+ [+ ("oauth_only_source", ExternalDataSourceType.HUBSPOT, ValueError),+ ("custom_has_no_kind", ExternalDataSourceType.CUSTOM, UnknownCredentialKindError),+ ]+ )+ def test_source_without_a_typed_in_auth_type_gets_no_row(+ self, _name: str, source_type: ExternalDataSourceType, error: type[Exception]+ ) -> None:+ source = self._source(source_type)++ with self.assertRaises(error):+ WarehouseSourceCredentialsStore.create(source, {"token": "fake"})+ assert source.credentials_integration_id is None+ 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(+ [+ ("none", lambda store_pk, other: None),+ ("not_a_number", lambda store_pk, other: "abc"),+ ("missing_pk", lambda store_pk, other: str(store_pk + 1000)),+ ("other_team", lambda store_pk, other: str(other["other_team"])),+ ("other_kind", lambda store_pk, other: str(other["stripe"])),+ ("unmarked_row_of_same_kind", lambda store_pk, other: str(other["native_postgres"])),+ # The credentials service is not readable yet, so a UUID resolves to no row.+ ("uuid", lambda store_pk, other: str(uuid4())),+ # Only the canonical form of the reference counts, so a bad write never reads another row.+ ("leading_zero", lambda store_pk, other: f"0{store_pk}"),+ ("whitespace", lambda store_pk, other: f" {store_pk}"),+ ("signed", lambda store_pk, other: f"+{store_pk}"),+ ("uuid_upper_case", lambda store_pk, other: str(uuid4()).upper()),+ ("empty", lambda store_pk, other: ""),+ ]+ )+ def test_a_reference_the_source_cannot_use_is_no_row(self, _name: str, ref_of: Any) -> None:+ source = self._source()+ store_pk = self._create(source, PG_FIELDS)+ other_team = Team.objects.create(organization=self.organization, name="Other")+ other = {+ "other_team": self._create(self._source(team=other_team), PG_FIELDS),+ "stripe": self._create(self._source(ExternalDataSourceType.STRIPE), STRIPE_FIELDS),+ "native_postgres": IntegrationManager.postgresql.credentials.create(+ self.team.id, external_id="native", config={}, sensitive_config={"fields": PG_FIELDS}+ ).id,+ }++ source.credentials_integration_id = ref_of(store_pk, other)++ 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++ @parameterized.expand(+ [("empty_dict", {}), ("no_fields_key", {"other": 1}), ("fields_not_a_mapping", {"fields": 5})]+ )+ def test_unreadable_row_is_reported_distinctly(self, _name: str, stored: dict[str, Any]) -> None:+ source = self._source()+ pk = self._create(source, PG_FIELDS)+ row = _row(pk)+ row.sensitive_config = stored+ row.save()++ with self.assertRaises(CredentialsUnreadableError) as raised:+ WarehouseSourceCredentialsStore.get(source)+ assert "fake-password" not in str(raised.exception)+ assert WarehouseSourceCredentialsStore.get_many([source]) == {source.id: CredentialsUnreadable()}++ def test_undecryptable_leaf_is_unreadable_and_extra_layers_are_peeled(self) -> None:+ source, double_encrypted = self._source(), self._source()+ field = cast(EncryptedJSONField, Integration._meta.get_field("sensitive_config"))+ foreign_ciphertext = Fernet(Fernet.generate_key()).encrypt(b"fake-password").decode()+ self._create(source, {"host": "db.example.com", "password": foreign_ciphertext})+ self._create(double_encrypted, {"password": field.encrypt("fake-password")})++ with self.assertRaises(CredentialsUnreadableError):+ WarehouseSourceCredentialsStore.get(source)+ assert WarehouseSourceCredentialsStore.get(double_encrypted) == {"password": "fake-password"}+ assert WarehouseSourceCredentialsStore.get_many([source, double_encrypted]) == {+ source.id: CredentialsUnreadable(),+ double_encrypted.id: {"password": "fake-password"},+ }++ def test_get_many_uses_one_query_per_team_and_source_type_and_skips_rows_a_source_cannot_use(self) -> None:+ postgres, postgres_b, stripe, without_ref, wrong_kind, uuid_ref = (+ self._source(),+ self._source(),+ self._source(ExternalDataSourceType.STRIPE),+ self._source(),+ self._source(),+ self._source(),+ )+ self._create(postgres, PG_FIELDS)+ self._create(postgres_b, {**PG_FIELDS, "host": "b.example.com"})+ wrong_kind.credentials_integration_id = str(self._create(stripe, STRIPE_FIELDS))+ uuid_ref.credentials_integration_id = str(uuid4())++ with self.assertNumQueries(2):+ result = WarehouseSourceCredentialsStore.get_many(+ [postgres, postgres_b, stripe, without_ref, wrong_kind, uuid_ref]+ )++ assert result == {+ postgres.id: PG_FIELDS,+ postgres_b.id: {**PG_FIELDS, "host": "b.example.com"},+ stripe.id: STRIPE_FIELDS,+ }++ @parameterized.expand(+ [+ # (name, other user, new fields, allow_shared, outcome)+ ("sole_user_secret_change", None, {**PG_FIELDS, "password": "new"}, False, "in_place"),+ ("sole_user_host_change", None, {**PG_FIELDS, "host": "new.example.com"}, False, "in_place"),+ ("shared_secret_change", "source", {**PG_FIELDS, "password": "new"}, False, "conflict"),+ ("shared_secret_change_confirmed", "source", {**PG_FIELDS, "password": "new"}, True, "in_place"),+ ("shared_with_a_workflow", "workflow", {**PG_FIELDS, "password": "new"}, False, "conflict"),+ ("shared_host_change", "source", {**PG_FIELDS, "host": "new.example.com"}, False, "new_row"),+ ("shared_user_change", "source", {**PG_FIELDS, "user": "writer"}, True, "new_row"),+ ("shared_tunnel_change", "source", {**PG_FIELDS, "ssh_tunnel": {"enabled": "False"}}, False, "new_row"),+ ("shared_same_fields_as_strings", "source", {**PG_FIELDS, "port": 5432}, False, "conflict"),+ ]+ )+ def test_update_of_a_shared_row_needs_confirmation_or_makes_a_new_row(+ self, _name: str, other_user: str | None, new_fields: dict[str, Any], allow_shared: bool, outcome: str+ ) -> None:+ source = self._source()+ pk = self._create(source, PG_FIELDS)+ if other_user == "source":+ self._referencing(pk)+ workflows = (+ [WorkflowSummary(id="wf1", name="Nightly sync", status="active")] if other_user == "workflow" else []+ )++ with patch(+ "products.workflows.backend.integration_usages.get_active_workflows_using_integration",+ return_value=workflows,+ ):+ if outcome == "conflict":+ with self.assertRaises(SharedCredentialsError) as raised:+ WarehouseSourceCredentialsStore.update(source, new_fields, allow_shared=allow_shared)+ assert raised.exception.integration_id == pk+ assert [usage.type for usage in raised.exception.usages] == [+ "workflow" if other_user == "workflow" else "warehouse_source"+ ]+ assert source.credentials_integration_id == str(pk)+ assert WarehouseSourceCredentialsStore.get(source) == PG_FIELDS+ return+ reference = WarehouseSourceCredentialsStore.update(source, new_fields, allow_shared=allow_shared)++ new_pk = reference.legacy_id+ assert new_pk is not None+ assert source.credentials_integration_id == str(new_pk)+ if outcome == "in_place":+ assert new_pk == pk+ else:+ assert new_pk != pk+ assert self._fields_of_row(pk) == PG_FIELDS+ # The source points at the new row only when the caller saves it with its inputs.+ assert ExternalDataSource.objects.get(id=source.id).credentials_integration_id == str(pk)+ assert WarehouseSourceCredentialsStore.get(source) == {+ key: str(value) if key == "port" else value for key, value in new_fields.items()+ }+ assert _row(new_pk).config[WAREHOUSE_SOURCE_TYPE_CONFIG_KEY] == "Postgres"++ @parameterized.expand(+ [+ # (name, source type, fields, changed path, new value, outcome)+ ("nested_user", ExternalDataSourceType.SNOWFLAKE, SNOWFLAKE_FIELDS, "auth_type.user", "writer", "new_row"),+ (+ "nested_secret",+ ExternalDataSourceType.SNOWFLAKE,+ SNOWFLAKE_FIELDS,+ "auth_type.password",+ "new",+ "conflict",+ ),+ (+ "url_password",+ ExternalDataSourceType.POSTGRES,+ PG_URL_FIELDS,+ "connection_string",+ "postgresql://reader:[email protected]:5432/app?sslmode=require",+ "conflict",+ ),+ (+ "url_query",+ ExternalDataSourceType.POSTGRES,+ PG_URL_FIELDS,+ "connection_string",+ "postgresql://reader:[email protected]:5432/app?sslmode=disable",+ "conflict",+ ),+ (+ "url_host",+ ExternalDataSourceType.POSTGRES,+ PG_URL_FIELDS,+ "connection_string",+ "postgresql://reader:[email protected]:5432/app",+ "new_row",+ ),+ (+ "url_database",+ ExternalDataSourceType.POSTGRES,+ PG_URL_FIELDS,+ "connection_string",+ "postgresql://reader:[email protected]:5432/other",+ "new_row",+ ),+ (+ "mongodb_auth_source",+ ExternalDataSourceType.MONGODB,+ {"connection_string": "mongodb://reader:[email protected]/app?authSource=admin"},+ "connection_string",+ "mongodb://reader:[email protected]/app?authSource=other",+ "new_row",+ ),+ (+ "mongodb_default_auth_source",+ ExternalDataSourceType.MONGODB,+ {"connection_string": "mongodb://reader:[email protected]/app"},+ "connection_string",+ "mongodb://reader:[email protected]/app?authSource=other",+ "new_row",+ ),+ (+ "mongodb_no_path_auth_source",+ ExternalDataSourceType.MONGODB,+ {"connection_string": "mongodb+srv://reader:[email protected]?authSource=admin"},+ "connection_string",+ "mongodb+srv://reader:[email protected]?authSource=other",+ "new_row",+ ),+ (+ "mongodb_password",+ ExternalDataSourceType.MONGODB,+ {"connection_string": "mongodb://reader:[email protected]/app?authSource=admin"},+ "connection_string",+ "mongodb://reader:[email protected]/app?authSource=admin",+ "conflict",+ ),+ (+ "pairs_password",+ ExternalDataSourceType.MSSQL,+ MSSQL_ADO_FIELDS,+ "connection_string",+ "Server=db.example.com,1433;User Id=reader;Password=new;Database=app",+ "conflict",+ ),+ (+ "pairs_user",+ ExternalDataSourceType.MSSQL,+ MSSQL_ADO_FIELDS,+ "connection_string",+ "Server=db.example.com,1433;User Id=writer;Password=fake-password;Database=app",+ "new_row",+ ),+ (+ "tunnel_key",+ ExternalDataSourceType.POSTGRES,+ PG_TUNNEL_FIELDS,+ "ssh_tunnel.auth_type.private_key",+ "new",+ "conflict",+ ),+ (+ "tunnel_passphrase",+ ExternalDataSourceType.POSTGRES,+ PG_TUNNEL_FIELDS,+ "ssh_tunnel.auth_type.passphrase",+ "new",+ "conflict",+ ),+ (+ "tunnel_username",+ ExternalDataSourceType.POSTGRES,+ PG_TUNNEL_FIELDS,+ "ssh_tunnel.auth_type.username",+ "other",+ "new_row",+ ),+ (+ "tunnel_host",+ ExternalDataSourceType.POSTGRES,+ PG_TUNNEL_FIELDS,+ "ssh_tunnel.host",+ "other.example.com",+ "new_row",+ ),+ (+ "tunnel_enabled_case",+ ExternalDataSourceType.POSTGRES,+ PG_TUNNEL_FIELDS,+ "ssh_tunnel.enabled",+ "true",+ "conflict",+ ),+ ]+ )+ def test_shared_row_identity_reads_nested_fields_and_ignores_secrets(+ self,+ _name: str,+ source_type: ExternalDataSourceType,+ fields: dict[str, Any],+ path: str,+ value: Any,+ outcome: str,+ ) -> None:+ source = self._source(source_type)+ pk = self._create(source, fields)+ self._referencing(pk, source_type)+ new_fields = _with(fields, path, value)++ if outcome == "conflict":+ with self.assertRaises(SharedCredentialsError):+ WarehouseSourceCredentialsStore.update(source, new_fields)+ assert WarehouseSourceCredentialsStore.get(source) == fields+ return+ new_pk = WarehouseSourceCredentialsStore.update(source, new_fields).legacy_id+ assert new_pk is not None and new_pk != pk+ assert self._fields_of_row(pk, source_type) == fields+ assert WarehouseSourceCredentialsStore.get(source) == new_fields++ def test_update_of_a_row_of_another_kind_raises(self) -> None:+ stripe = self._source(ExternalDataSourceType.STRIPE)+ stripe_pk = self._create(stripe, STRIPE_FIELDS)+ postgres = self._source()+ postgres.credentials_integration_id = str(stripe_pk)++ with self.assertRaises(CredentialsNotFoundError):+ 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:+ 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++ 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={})++ 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++ @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),+ ("top_level_string", {"linear_integration_id": "7"}, True),+ ("nested", {"auth": {"hubspot_integration_id": 7}}, True),+ # The typed-in pointer lives in the column, so a stale input of the same name is not a pointer.+ ("column_name_in_inputs", {"credentials_integration_id": "7"}, False),+ ("other_integration", {"linear_integration_id": 8}, False),+ ("not_a_pointer_key", {"workspace_id": 7}, False),+ ("no_inputs", None, False),+ ]+ )+ def test_reference_detection_in_inputs(self, _name: str, inputs: dict[str, Any] | None, expected: bool) -> None:+ source = self._source()+ source.job_inputs = inputs+ source.save()++ found = list_sources_using_integration(self.team.id, 7)++ assert [ref.id for ref in found] == ([source.id] if expected else [])++ @parameterized.expand(+ [+ ("column", "7", None, False, True),+ ("column_and_inputs_count_once", "7", {"linear_integration_id": "7"}, False, True),+ ("deleted_source", "7", None, True, False),+ ("other_row", "8", None, False, False),+ ("leading_zero", "07", None, False, False),+ ("uuid", "0b7e8c3a-5f4d-4e2a-9c1b-2d3e4f5a6b7c", None, False, False),+ ]+ )+ def test_reference_detection_by_column(+ self, _name: str, column: str, inputs: dict[str, Any] | None, deleted: bool, expected: bool+ ) -> None:+ source = self._source()+ source.credentials_integration_id = column+ source.job_inputs = inputs+ source.deleted = deleted+ source.save()++ found = list_sources_using_integration(self.team.id, 7)++ assert [(ref.id, ref.unreadable) for ref in found] == ([(source.id, False)] if expected else [])++ @parameterized.expand(+ [+ # (name, row, broken source type, encrypted pointer, counted)+ ("oauth_row_of_its_kind", "oauth", ExternalDataSourceType.HUBSPOT, False, True),+ ("oauth_row_of_its_kind_encrypted_pointer", "oauth", ExternalDataSourceType.HUBSPOT, True, True),+ ("oauth_row_of_another_kind", "oauth", ExternalDataSourceType.POSTGRES, False, False),+ # The typed-in pointer is in the column, which always reads, so broken inputs say nothing about it.+ ("typed_in_row_of_its_kind", "typed_in", ExternalDataSourceType.POSTGRES, False, False),+ ("typed_in_row_of_its_kind_encrypted_pointer", "typed_in", ExternalDataSourceType.POSTGRES, True, False),+ ]+ )+ def test_a_source_with_unreadable_inputs_counts_as_a_user_of_an_oauth_row_of_its_kind(+ self, _name: str, row: str, broken_type: ExternalDataSourceType, encrypted_pointer: bool, counted: bool+ ) -> None:+ editor = self._source()+ pk = (+ self._create(editor, PG_FIELDS)+ if row == "typed_in"+ else IntegrationManager.hubspot.oauth.create(self.team.id, external_id="H1", config={}).id+ )+ broken = self._source(broken_type)+ broken.job_inputs = (+ {"auth": {"hubspot_integration_id": Fernet(Fernet.generate_key()).encrypt(str(pk).encode()).decode()}}+ if encrypted_pointer+ else "not json"+ )+ broken.save()++ found = list_sources_using_integration(self.team.id, pk)++ expected = [(broken.id, True)] if counted else []+ if row == "typed_in":+ expected = [(editor.id, False)]+ assert WarehouseSourceCredentialsStore.update(editor, {**PG_FIELDS, "password": "new"}).legacy_id == pk+ assert [(ref.id, ref.unreadable) for ref in found] == expected++ def test_conflict_response_names_the_other_users(self) -> None:+ source = self._source()+ pk = self._create(source, PG_FIELDS)+ self._referencing(pk)+ with self.assertRaises(SharedCredentialsError) as raised:+ WarehouseSourceCredentialsStore.update(source, {**PG_FIELDS, "password": "new"})++ response = shared_credentials_conflict_response(raised.exception)++ assert response.status_code == 409+ assert response.data["code"] == "shared_credentials"+ assert response.data["integration_id"] == pk+ assert [usage["type"] for usage in response.data["usages"]] == ["warehouse_source"]+ assert "update_shared_credentials=true" in response.data["detail"]+++class TestWarehouseSourceUsageProvider(BaseTest):+ def _source(+ self,+ job_inputs: dict[str, Any],+ prefix: str | None = None,+ deleted: bool = False,+ credentials_integration_id: str | None = None,+ ) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team=self.team,+ source_id=str(uuid4()),+ connection_id=str(uuid4()),+ status="Completed",+ source_type=ExternalDataSourceType.POSTGRES,+ job_inputs=job_inputs,+ prefix=prefix,+ deleted=deleted,+ credentials_integration_id=credentials_integration_id,+ )++ def _row(self) -> IntegrationRecord:+ return IntegrationManager.source("postgresql").credentials.create(+ self.team.id, external_id="pg", config={WAREHOUSE_SOURCE_TYPE_CONFIG_KEY: "Postgres"}+ )++ @parameterized.expand(+ [+ ("credentials_column", None, "prod", "Postgres (prod)"),+ ("oauth_pointer_without_prefix", "linear_integration_id", None, "Postgres"),+ ]+ )+ def test_the_sdk_reports_a_source_that_points_at_the_row(+ self, _name: str, inputs_key: str | None, prefix: str | None, name: str+ ) -> None:+ row = self._row()+ pointer: dict[str, Any] = (+ {"job_inputs": {inputs_key: str(row.id)}}+ if inputs_key+ else {"job_inputs": {}, "credentials_integration_id": str(row.id)}+ )+ source = self._source(prefix=prefix, **pointer)+ self._source(deleted=True, **pointer)++ assert IntegrationManager.any.with_source_rows().usages(self.team.id, row.id) == [+ IntegrationUsage(type="warehouse_source", id=str(source.id), name=name)+ ]++ def test_delete_of_a_used_row_raises_and_keeps_the_row(self) -> None:+ row = self._row()+ self._source({}, credentials_integration_id=str(row.id))++ with self.assertRaises(IntegrationInUse) as raised:+ IntegrationManager.source("postgresql").any.delete(self.team.id, row.id)++ assert [usage.type for usage in raised.exception.usages] == ["warehouse_source"]+ assert IntegrationManager.any.with_source_rows().get(self.team.id, row.id).id == row.id+++def _typed_in_source_types() -> list[str]:+ """Source types that can have a typed-in row: connection fields, and no top-level OAuth reference."""+ with open(CLASSIFICATION_AUDIT_PATH) as audit:+ rows = list(csv.DictReader(audit))+ return [+ row["source_type"]+ for row in rows+ if row["credential_kind"]+ and row["connection_fields"]+ and not any("=" not in name for name in row["reference_fields"].split())+ ]+++class TestCredentialAuthTypes(SimpleTestCase):+ def test_every_typed_in_source_type_has_an_auth_type_its_kind_supports(self) -> None:+ source_types = _typed_in_source_types()+ assert len(source_types) > 800++ for source_type in source_types:+ auth_type = typed_in_auth_type(source_type)+ assert auth_type in kind_auth_types(CREDENTIAL_KINDS[source_type]).supported, source_type++ def test_every_credential_kind_is_a_valid_stored_kind(self) -> None:+ stored_kinds = {value for value, _ in integration_kind_choices()}+ known = catalogued_kinds()++ for kind in set(CREDENTIAL_KINDS.values()):+ assert kind in stored_kinds, kind+ assert kind in known, kind++ @parameterized.expand(+ [+ ("oauth_only_source", ExternalDataSourceType.LINEAR, ValueError),+ ("custom_has_no_kind", ExternalDataSourceType.CUSTOM, UnknownCredentialKindError),+ ]+ )+ def test_typed_in_auth_type_rejects_a_source_without_typed_in_credentials(+ self, _name: str, source_type: ExternalDataSourceType, error: type[Exception]+ ) -> None:+ with self.assertRaises(error):+ typed_in_auth_type(source_type.value)+++class TestCredentialIdentityFields(SimpleTestCase):+ @parameterized.expand(+ [+ ("postgres", ExternalDataSourceType.POSTGRES, {"connection_string", "host", "port", "ssh_tunnel", "user"}),+ (+ "supabase_inherits",+ ExternalDataSourceType.SUPABASE,+ {"connection_string", "host", "port", "ssh_tunnel", "user"},+ ),+ ("mysql", ExternalDataSourceType.MYSQL, {"host", "port", "ssh_tunnel", "user"}),+ ("snowflake_nested_user", ExternalDataSourceType.SNOWFLAKE, {"account_id", "connection_string", "user"}),+ ("trino_nested_user", ExternalDataSourceType.TRINO, {"host", "port", "user"}),+ ("mongodb", ExternalDataSourceType.MONGODB, {"connection_string"}),+ ("twilio_account", ExternalDataSourceType.TWILIO, {"account_sid"}),+ ("okta_host_field", ExternalDataSourceType.OKTA, {"okta_domain"}),+ ("freshservice_host_field", ExternalDataSourceType.FRESHSERVICE, {"domain"}),+ ("hatchet_host_field", ExternalDataSourceType.HATCHET, {"host"}),+ ("stripe_none", ExternalDataSourceType.STRIPE, set()),+ ("zendesk_none", ExternalDataSourceType.ZENDESK, set()),+ ("custom_none", ExternalDataSourceType.CUSTOM, set()),+ ]+ )+ def test_identity_fields_match_the_old_rule(+ self, _name: str, source_type: ExternalDataSourceType, expected: set[str]+ ) -> None:+ assert SourceRegistry.get_source(source_type).credential_identity_fields == expecteddiff --git a/products/workflows/backend/integration_usages.py b/products/workflows/backend/integration_usages.pynew file mode 100644index 000000000000..28e9921692ea--- /dev/null+++ b/products/workflows/backend/integration_usages.py@@ -0,0 +1,14 @@+"""The active workflows that use an integration row. The integrations SDK loads this module."""++from posthog.integrations import IntegrationUsage++from products.workflows.backend.facade.api import get_active_workflows_using_integration++WORKFLOW_USAGE_TYPE = "workflow"+++def integration_usages(team_id: int, integration_id: int) -> list[IntegrationUsage]:+ return [+ IntegrationUsage(type=WORKFLOW_USAGE_TYPE, id=flow.id, name=flow.name or flow.id)+ for flow in get_active_workflows_using_integration(team_id=team_id, integration_id=integration_id)+ ]diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ec27fb8d730c..9e7b7e6173c6 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -66677,6 +66677,90 @@ export namespace Schemas {*/export interface IntegrationConfig {readonly id: number;+ /**+ * The provider of the integration, for example 'slack' or 'github'. A create accepts only the kinds that PostHog connects here. Data warehouse sources also store their typed-in credentials as integrations, under a kind per source type.+ * @maxLength 32+ */+ kind: string;+ /** How this integration authenticates with the provider: `oauth` for a connection the provider manages (an OAuth grant or an app installation), `token` for one static secret, or `credentials` for several typed-in fields. A kind can have several auth types.+ *+ * * `oauth` - OAuth+ * * `token` - Token+ * * `credentials` - Credentials */+ readonly auth_type: IntegrationAuthTypeEnum;+ config?: unknown;+ readonly created_at: string;+ readonly created_by: UserBasic;+ readonly errors: string;+ readonly display_name: string;+ /** Slack only: whether reconnecting can request the files:write scope. */+ readonly files_write_requestable: boolean;+ /**+ * GitHub only, null otherwise. Whether another project's GitHub integration references the same App installation. When false, disconnecting this integration also uninstalls the GitHub App from the connected account or organization and removes personal GitHub connections that share it.+ * @nullable+ */+ readonly installation_shared: boolean | null;+ /** GitHub only, null otherwise. `unavailable` means the App was uninstalled or suspended on GitHub and PostHog can no longer mint tokens for it; `connected` otherwise. */+ readonly installation_status: InstallationStatusEnum | null;+ }++ /**+ * The request schema of a create. A create accepts only the public kinds, so the schema lists them.+ */+ export interface IntegrationConfigCreate {+ readonly id: number;+ /** The provider of the integration, for example 'slack' or 'github'.+ *+ * * `anthropic` - Anthropic+ * * `apple-ads` - Apple Ads+ * * `apns` - Apple Push+ * * `aws-redshift` - Aws Redshift+ * * `aws-s3` - Aws S3+ * * `azure-blob` - Azure Blob+ * * `bing-ads` - Bing Ads+ * * `clickup` - Clickup+ * * `customerio-app` - Customerio App+ * * `customerio-track` - Customerio Track+ * * `customerio-webhook` - Customerio Webhook+ * * `databricks` - Databricks+ * * `email` - Email+ * * `firebase` - Firebase+ * * `github` - Github+ * * `gitlab` - Gitlab+ * * `google-ads` - Google Ads+ * * `google-analytics` - Google Analytics+ * * `google-calendar` - Google Calendar+ * * `google-cloud-service-account` - Google Cloud Service Account+ * * `google-cloud-storage` - Google Cloud Storage+ * * `google-pubsub` - Google Pubsub+ * * `google-search-console` - Google Search Console+ * * `google-sheets` - Google Sheets+ * * `helpscout` - Helpscout+ * * `hubspot` - Hubspot+ * * `instagram` - Instagram+ * * `intercom` - Intercom+ * * `jira` - Jira+ * * `linear` - Linear+ * * `linkedin-ads` - Linkedin Ads+ * * `meta-ads` - Meta Ads+ * * `pardot` - Pardot+ * * `pinterest-ads` - Pinterest Ads+ * * `postgresql` - Postgresql+ * * `posthog` - Posthog+ * * `reddit-ads` - Reddit Ads+ * * `twitter-ads` - Twitter Ads+ * * `resend` - Resend+ * * `s3-compatible` - S3 Compatible+ * * `salesforce` - Salesforce+ * * `slack` - Slack+ * * `slack-posthog-code` - Slack Posthog Code+ * * `snapchat` - Snapchat+ * * `snowflake` - Snowflake+ * * `stripe` - Stripe+ * * `tiktok-ads` - Tiktok Ads+ * * `twilio` - Twilio+ * * `vercel` - Vercel+ * * `youtube-analytics` - Youtube Analytics */kind: IntegrationKindEnum;/** How this integration authenticates with the provider: `oauth` for a connection the provider manages (an OAuth grant or an app installation), `token` for one static secret, or `credentials` for several typed-in fields. A kind can have several auth types.*@@ -80722,7 +80806,8 @@ export namespace Schemas {*/export interface SessionRecordingExternalReferenceIntegration {readonly id: number;- readonly kind: IntegrationKindEnum;+ /** The provider of the integration, for example 'github'. */+ readonly kind: string;readonly display_name: string;}@@ -90225,7 +90310,11 @@ export namespace Schemas {*/export interface PatchedIntegrationConfig {readonly id?: number;- kind?: IntegrationKindEnum;+ /**+ * The provider of the integration, for example 'slack' or 'github'. A create accepts only the kinds that PostHog connects here. Data warehouse sources also store their typed-in credentials as integrations, under a kind per source type.+ * @maxLength 32+ */+ kind?: string;/** How this integration authenticates with the provider: `oauth` for a connection the provider manages (an OAuth grant or an app installation), `token` for one static secret, or `credentials` for several typed-in fields. A kind can have several auth types.** * `oauth` - OAuth