Skip to content

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

feat(warehouse-destinations): return the connected integration through a connect token (#128058)

Tom Owers15039c700de9
diff --git a/posthog/integrations/README.md b/posthog/integrations/README.md
index 6b1ea67ca6ca..ced3301aee55 100644
--- a/posthog/integrations/README.md
+++ b/posthog/integrations/README.md
@@ -104,7 +104,7 @@ An OAuth accessor (`IntegrationManager.<kind>.oauth`) also refreshes access toke
## Rows are read-only
The SDK returns rows typed as `IntegrationRecord`, a read-only `Protocol`:
-`id`, `team_id`, `kind`, `integration_id`, `config`, `sensitive_config`, `errors`, `created_at`, `created_by_id`, `auth_type`, `access_token`, `refresh_token` and `can_be_managed_by_creator(user_id)`.
+`id`, `team_id`, `kind`, `integration_id`, `config`, `sensitive_config`, `errors`, `created_at`, `created_by_id`, `auth_type`, `display_name`, `access_token`, `refresh_token` and `can_be_managed_by_creator(user_id)`.
`config` and `sensitive_config` are `Mapping`s, so mypy rejects `row.config["x"] = 1`.
Mypy also rejects `.save()`, `.delete()`, `.refresh_from_db()`, managers and related rows such as `row.team`.
Use `row.team_id` and `row.created_by_id`, and load the team or the user from their own models.
diff --git a/posthog/integrations/contracts.py b/posthog/integrations/contracts.py
index 21cce799df3d..f8fa8672a4d7 100644
--- a/posthog/integrations/contracts.py
+++ b/posthog/integrations/contracts.py
@@ -58,6 +58,10 @@ class IntegrationRecord(Protocol):
@property
def auth_type(self) -> str: ...
+ # The name the UI shows for the connection, for example the account or host.
+ @property
+ def display_name(self) -> str: ...
+
# The decrypted `sensitive_config["access_token"]`. Raises `UndecryptedIntegrationSecretError`
# when the stored value cannot be decrypted.
@property
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index 4980e6bc27fb..f944a2753f31 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -778,6 +778,13 @@ CACHES["metrics_variable_options"] = {
"LOCATION": REDIS_URL,
}
+# Warehouse destination connect tokens are polled right after they are written, and completion claims a
+# token with SETNX. A lagging replica would report a fresh token as expired, so read from the writer.
+CACHES["warehouse_destination_connect"] = {
+ **CACHES["default"],
+ "LOCATION": REDIS_URL,
+}
+
# Dedicated cache for the feature flags service (if configured)
# Django only writes to this cache (never reads), so no reader URL needed
if FLAGS_REDIS_URL:
@@ -845,6 +852,7 @@ if TEST:
CACHES["ingress_dedup"] = CACHES["default"]
CACHES["task_artifact_preview"] = CACHES["default"]
CACHES["metrics_variable_options"] = CACHES["default"]
+ CACHES["warehouse_destination_connect"] = CACHES["default"]
# Cache timeout for materialized columns metadata (in seconds)
MATERIALIZED_COLUMNS_CACHE_TIMEOUT: int = get_from_env("MATERIALIZED_COLUMNS_CACHE_TIMEOUT", 900, type_cast=int)
diff --git a/products/data_warehouse/frontend/scenes/DestinationConnectScene/DestinationConnectScene.tsx b/products/data_warehouse/frontend/scenes/DestinationConnectScene/DestinationConnectScene.tsx
index 97cf8933ec0d..7218161115d7 100644
--- a/products/data_warehouse/frontend/scenes/DestinationConnectScene/DestinationConnectScene.tsx
+++ b/products/data_warehouse/frontend/scenes/DestinationConnectScene/DestinationConnectScene.tsx
@@ -24,7 +24,8 @@ export const scene: SceneExport = {
export function DestinationConnectScene(): JSX.Element {
const { featureFlags } = useValues(featureFlagLogic)
- const { kind, destinationDefinition, isModalOpen, integrationId } = useValues(destinationConnectSceneLogic)
+ const { kind, destinationDefinition, isModalOpen, integrationId, handBackStatus } =
+ useValues(destinationConnectSceneLogic)
const { setModalOpen, setIntegrationId } = useActions(destinationConnectSceneLogic)
if (!featureFlags[FEATURE_FLAGS.WAREHOUSE_MULTI_DESTINATION]) {
@@ -63,12 +64,24 @@ export function DestinationConnectScene(): JSX.Element {
/>
<div className="max-w-200">
{integrationId !== null ? (
- <LemonBanner type="success">
+ <LemonBanner type={handBackStatus === 'sending' ? 'info' : 'success'}>
<p className="font-semibold mb-1">{typeLabel} connection saved</p>
- <p className="m-0 text-sm">
- Copy this connection id into your chat: <code>{integrationId}</code>. The assistant uses it
- to create the destination, which doesn't exist yet. Then you can close this tab.
- </p>
+ {handBackStatus === 'sending' ? (
+ <p className="m-0 text-sm">Sending the connection to the assistant…</p>
+ ) : handBackStatus === 'sent' ? (
+ <p className="m-0 text-sm">
+ The assistant can see this connection now. Go back to your terminal or chat to finish
+ creating the destination. You can close this tab.
+ </p>
+ ) : (
+ <p className="m-0 text-sm">
+ {handBackStatus === 'failed'
+ ? "We couldn't send the connection to the assistant. "
+ : ''}
+ Copy this connection id into your chat: <code>{integrationId}</code>. The assistant uses
+ it to create the destination, which doesn't exist yet. Then you can close this tab.
+ </p>
+ )}
</LemonBanner>
) : (
!isModalOpen && (
diff --git a/products/data_warehouse/frontend/scenes/DestinationConnectScene/destinationConnectSceneLogic.test.ts b/products/data_warehouse/frontend/scenes/DestinationConnectScene/destinationConnectSceneLogic.test.ts
index dc703464aebe..b7c780cb2e93 100644
--- a/products/data_warehouse/frontend/scenes/DestinationConnectScene/destinationConnectSceneLogic.test.ts
+++ b/products/data_warehouse/frontend/scenes/DestinationConnectScene/destinationConnectSceneLogic.test.ts
@@ -1,6 +1,8 @@
import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
+import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { destinationConnectSceneLogic } from './destinationConnectSceneLogic'
@@ -46,4 +48,31 @@ describe('destinationConnectSceneLogic', () => {
)
expect(viewed).toHaveLength(1)
})
+
+ it.each([
+ { search: '?kind=snowflake&token=abc_123', status: 200, expected: 'sent', requested: true },
+ { search: '?kind=snowflake&token=abc_123', status: 404, expected: 'failed', requested: true },
+ { search: '?kind=snowflake', status: 200, expected: null, requested: false },
+ ])(
+ 'hands the saved connection back for $search when the API returns $status',
+ async ({ search, status, expected, requested }) => {
+ const requests: unknown[] = []
+ useMocks({
+ post: {
+ '/api/projects/:team_id/external_data_destinations/connect_link_complete/': async ({ request }) => {
+ requests.push(await request.json())
+ return [status, {}]
+ },
+ },
+ })
+ router.actions.push(`/data-warehouse/connect-destination${search}`)
+
+ await expectLogic(destinationConnectSceneLogic, () => {
+ destinationConnectSceneLogic.actions.setIntegrationId(42)
+ }).toFinishAllListeners()
+
+ expect(destinationConnectSceneLogic.values.handBackStatus).toEqual(expected)
+ expect(requests).toEqual(requested ? [{ connect_token: 'abc_123', integration_id: 42 }] : [])
+ }
+ )
})
diff --git a/products/data_warehouse/frontend/scenes/DestinationConnectScene/destinationConnectSceneLogic.ts b/products/data_warehouse/frontend/scenes/DestinationConnectScene/destinationConnectSceneLogic.ts
index e46486977eb3..41ecc14d346f 100644
--- a/products/data_warehouse/frontend/scenes/DestinationConnectScene/destinationConnectSceneLogic.ts
+++ b/products/data_warehouse/frontend/scenes/DestinationConnectScene/destinationConnectSceneLogic.ts
@@ -1,20 +1,26 @@
-import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { urlToAction } from 'kea-router'
import posthog from 'posthog-js'
import { Scene } from 'scenes/sceneTypes'
+import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { Breadcrumb, IntegrationKind } from '~/types'
+import { externalDataDestinationsConnectLinkCompleteCreate } from 'products/warehouse_sources/frontend/generated/api'
+
import { destinationTypeLabel } from '../../shared/components/DestinationIcon'
import { WAREHOUSE_DESTINATIONS } from '../../shared/destinations/destinationDefinitions'
import type { WarehouseDestinationDefinition } from '../../shared/destinations/types'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface destinationConnectSceneLogicValues {
+ currentTeamId: number | null // teamLogic
breadcrumbs: Breadcrumb[]
+ connectToken: string | null
destinationDefinition: WarehouseDestinationDefinition | null
+ handBackStatus: HandBackStatus | null
integrationId: number | null
isModalOpen: boolean
kind: string | null
@@ -22,6 +28,12 @@ export interface destinationConnectSceneLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface destinationConnectSceneLogicActions {
+ setConnectToken: (connectToken: string | null) => {
+ connectToken: string | null
+ }
+ setHandBackStatus: (status: HandBackStatus) => {
+ status: HandBackStatus
+ }
setIntegrationId: (integrationId: number) => {
integrationId: number
}
@@ -48,14 +60,35 @@ export type destinationConnectSceneLogicType = MakeLogicType<
destinationConnectSceneLogicMeta
>
+/** Whether the saved connection reached the agent that shared the link. Only links with a connect token try. */
+export type HandBackStatus = 'sending' | 'sent' | 'failed'
+
export const destinationConnectSceneLogic = kea<destinationConnectSceneLogicType>([
path(['products', 'dataWarehouse', 'destinationConnectSceneLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId']],
+ })),
actions({
setKind: (kind: string | null) => ({ kind }),
+ setConnectToken: (connectToken: string | null) => ({ connectToken }),
setModalOpen: (open: boolean) => ({ open }),
setIntegrationId: (integrationId: number) => ({ integrationId }),
+ setHandBackStatus: (status: HandBackStatus) => ({ status }),
}),
reducers({
+ connectToken: [
+ null as string | null,
+ {
+ setConnectToken: (_, { connectToken }) => connectToken,
+ },
+ ],
+ handBackStatus: [
+ null as HandBackStatus | null,
+ {
+ setKind: () => null,
+ setHandBackStatus: (_, { status }) => status,
+ },
+ ],
kind: [
null as string | null,
{
@@ -106,7 +139,7 @@ export const destinationConnectSceneLogic = kea<destinationConnectSceneLogicType
],
],
}),
- listeners(({ values }) => ({
+ listeners(({ actions, values }) => ({
setKind: () => {
if (values.destinationDefinition) {
posthog.capture('warehouse destination connect page viewed', {
@@ -115,10 +148,29 @@ export const destinationConnectSceneLogic = kea<destinationConnectSceneLogicType
})
}
},
- setIntegrationId: () => {
+ setIntegrationId: async ({ integrationId }) => {
posthog.capture('warehouse destination connection saved', {
integration_kind: values.kind,
destination_type: values.destinationDefinition?.type,
+ has_connect_token: values.connectToken !== null,
+ })
+ if (!values.connectToken || values.currentTeamId === null) {
+ return
+ }
+ actions.setHandBackStatus('sending')
+ try {
+ await externalDataDestinationsConnectLinkCompleteCreate(String(values.currentTeamId), {
+ connect_token: values.connectToken,
+ integration_id: integrationId,
+ })
+ actions.setHandBackStatus('sent')
+ } catch {
+ actions.setHandBackStatus('failed')
+ }
+ posthog.capture('warehouse destination connection handed back', {
+ integration_kind: values.kind,
+ destination_type: values.destinationDefinition?.type,
+ succeeded: values.handBackStatus === 'sent',
})
},
})),
@@ -129,6 +181,10 @@ export const destinationConnectSceneLogic = kea<destinationConnectSceneLogicType
if (kind !== values.kind) {
actions.setKind(kind)
}
+ const connectToken = typeof searchParams.token === 'string' ? searchParams.token : null
+ if (connectToken !== values.connectToken) {
+ actions.setConnectToken(connectToken)
+ }
},
})),
])
diff --git a/products/warehouse_sources/backend/presentation/destination_connect_tokens.py b/products/warehouse_sources/backend/presentation/destination_connect_tokens.py
new file mode 100644
index 000000000000..59fe4511a653
--- /dev/null
+++ b/products/warehouse_sources/backend/presentation/destination_connect_tokens.py
@@ -0,0 +1,141 @@
+"""Connect tokens hand the integration a user saves on the destination connect page back to the agent.
+
+The agent gets a token with the connect link. The page reports the saved integration against the token,
+and the agent reads the result with the token. Credentials never pass through the agent.
+"""
+
+import secrets
+import dataclasses
+from datetime import datetime, timedelta
+from typing import Any
+
+from django.core.cache import caches
+from django.db import models
+from django.utils import timezone
+
+from posthog.dataclasses import frozen
+from posthog.integrations import IntegrationManager, IntegrationNotFound
+
+CONNECT_TOKEN_TTL = timedelta(hours=1)
+_CACHE_KEY_PREFIX = "wh_dest_connect"
+# Pinned to the Redis writer: the agent polls a token right after it is issued, and a replica can lag.
+_CACHE_ALIAS = "warehouse_destination_connect"
+
+
+class DestinationConnectStatus(models.TextChoices):
+ PENDING = "pending", "Pending"
+ CONNECTED = "connected", "Connected"
+ EXPIRED = "expired", "Expired"
+
+
+@frozen
+class DestinationConnectToken:
+ token: str = dataclasses.field(repr=False)
+ team_id: int
+ user_id: int
+ integration_kind: str
+ expires_at: datetime
+ integration_id: int | None = None
+ display_name: str | None = None
+
+ def status(self, now: datetime) -> DestinationConnectStatus:
+ if self.integration_id is not None:
+ return DestinationConnectStatus.CONNECTED
+ if now >= self.expires_at:
+ return DestinationConnectStatus.EXPIRED
+ return DestinationConnectStatus.PENDING
+
+
+class ConnectTokenNotFound(LookupError):
+ """The token is unknown, expired, or belongs to another project."""
+
+
+class ConnectTokenOtherUser(PermissionError):
+ """The token was issued to another user."""
+
+
+class ConnectTokenInvalidIntegration(ValueError):
+ """The integration cannot complete this token."""
+
+
+def _cache_key(team_id: int, token: str) -> str:
+ return f"{_CACHE_KEY_PREFIX}:{team_id}:{token}"
+
+
+def _claim_key(team_id: int, token: str) -> str:
+ return f"{_cache_key(team_id, token)}:claim"
+
+
+def _save(record: DestinationConnectToken) -> None:
+ payload: dict[str, Any] = dataclasses.asdict(record)
+ payload["expires_at"] = record.expires_at.isoformat()
+ caches[_CACHE_ALIAS].set(
+ _cache_key(record.team_id, record.token), payload, timeout=int(CONNECT_TOKEN_TTL.total_seconds())
+ )
+
+
+def _load(team_id: int, token: str) -> DestinationConnectToken | None:
+ payload = caches[_CACHE_ALIAS].get(_cache_key(team_id, token))
+ if not isinstance(payload, dict):
+ return None
+ return DestinationConnectToken(**{**payload, "expires_at": datetime.fromisoformat(payload["expires_at"])})
+
+
+def issue_connect_token(*, team_id: int, user_id: int, integration_kind: str) -> DestinationConnectToken:
+ record = DestinationConnectToken(
+ token=secrets.token_urlsafe(32),
+ team_id=team_id,
+ user_id=user_id,
+ integration_kind=integration_kind,
+ expires_at=timezone.now() + CONNECT_TOKEN_TTL,
+ )
+ _save(record)
+ return record
+
+
+def complete_connect_token(*, team_id: int, user_id: int, token: str, integration_id: int) -> DestinationConnectToken:
+ record = _load(team_id, token)
+ if record is None:
+ raise ConnectTokenNotFound()
+ if record.user_id != user_id:
+ raise ConnectTokenOtherUser()
+ if record.integration_id == integration_id:
+ return record
+ if record.integration_id is not None:
+ raise ConnectTokenInvalidIntegration(
+ "This link already reported another connection. Ask the assistant for a new link."
+ )
+ if record.status(timezone.now()) == DestinationConnectStatus.EXPIRED:
+ raise ConnectTokenNotFound()
+
+ try:
+ integration = IntegrationManager.any.get(team_id, integration_id)
+ except IntegrationNotFound:
+ raise ConnectTokenInvalidIntegration("This connection does not exist in this project.")
+ if integration.kind != record.integration_kind:
+ raise ConnectTokenInvalidIntegration(
+ f"This link needs a '{record.integration_kind}' connection, not '{integration.kind}'."
+ )
+
+ # Two tabs can complete the same pending token at once. The first claim wins, so the token never
+ # switches integrations and the losing request fails like any other switch.
+ if not caches[_CACHE_ALIAS].add(
+ _claim_key(team_id, token), integration.id, timeout=int(CONNECT_TOKEN_TTL.total_seconds())
+ ):
+ if caches[_CACHE_ALIAS].get(_claim_key(team_id, token)) != integration.id:
+ raise ConnectTokenInvalidIntegration(
+ "This link already reported another connection. Ask the assistant for a new link."
+ )
+
+ completed = dataclasses.replace(record, integration_id=integration.id, display_name=integration.display_name)
+ # Saving resets the cache timeout, so the agent can read the result for a full TTL after the user saves.
+ _save(completed)
+ return completed
+
+
+def read_connect_token(*, team_id: int, user_id: int, token: str) -> DestinationConnectToken | None:
+ """The token's record, or None when it is unknown, gone from the cache, or another user's."""
+ record = _load(team_id, token)
+ if record is None or record.user_id != user_id:
+ return None
+ return record
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_destination.py b/products/warehouse_sources/backend/presentation/views/external_data_destination.py
index 42982eaaba91..26fc074c4a5f 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_destination.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_destination.py
@@ -4,10 +4,11 @@ from urllib.parse import quote
from django.conf import settings
from django.db import models, transaction
from django.db.models import Q
+from django.utils import timezone
from drf_spectacular.utils import extend_schema, extend_schema_field
from rest_framework import serializers, status, viewsets
-from rest_framework.exceptions import PermissionDenied, ValidationError
+from rest_framework.exceptions import NotAuthenticated, NotFound, PermissionDenied, ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
@@ -27,6 +28,16 @@ from products.warehouse_sources.backend.facade.models import (
ExternalDataSource,
ExternalDataSourceDestination,
)
+from products.warehouse_sources.backend.presentation.destination_connect_tokens import (
+ ConnectTokenInvalidIntegration,
+ ConnectTokenNotFound,
+ ConnectTokenOtherUser,
+ DestinationConnectStatus,
+ DestinationConnectToken,
+ complete_connect_token,
+ issue_connect_token,
+ read_connect_token,
+)
from products.warehouse_sources.backend.presentation.destination_connection_check import (
CONFIG_FAILURES,
DestinationConnectionCheckError,
@@ -113,9 +124,68 @@ class DestinationConnectLinkSerializer(serializers.Serializer):
"so credentials never pass through the agent or the chat."
)
)
+ connect_token = serializers.CharField(
+ help_text=(
+ "Secret token in the link. Pass it to the connect link status endpoint to learn which integration the "
+ "user saved. Only the user who asked for the link can read its status."
+ )
+ )
+ expires_at = serializers.DateTimeField(
+ help_text="When the link stops accepting a new connection. Ask for a new link after this time."
+ )
instructions = serializers.CharField(help_text="Next steps for the agent to relay to the user.")
+# The fields are not named `token`: PostHog reads a `token` parameter as a project API key.
+class DestinationConnectCompleteRequestSerializer(serializers.Serializer):
+ connect_token = serializers.CharField(max_length=128, help_text="The connect token from the connect link URL.")
+ integration_id = serializers.IntegerField(
+ min_value=1, help_text="Id of the integration the user saved on the connect page."
+ )
+
+
+class DestinationConnectStatusQuerySerializer(serializers.Serializer):
+ connect_token = serializers.CharField(max_length=128, help_text="The connect_token that the connect link returned.")
+
+
+class DestinationConnectStatusSerializer(serializers.Serializer):
+ status = serializers.ChoiceField(
+ choices=DestinationConnectStatus.choices,
+ help_text=(
+ "`pending`: the user has not saved a connection yet. `connected`: the user saved one, and "
+ "integration_id holds it. `expired`: the link is no longer valid, or it is unknown or belongs to "
+ "another user. Ask for a new link."
+ ),
+ )
+ integration_id = serializers.IntegerField(
+ allow_null=True,
+ help_text="Id of the saved integration when status is `connected`. Pass it to destination create.",
+ )
+ integration_kind = serializers.CharField(
+ allow_null=True, help_text="The integration kind the link is for. Null when status is `expired`."
+ )
+ display_name = serializers.CharField(
+ allow_null=True,
+ help_text="Name of the saved connection, such as the account or host, to confirm with the user.",
+ )
+
+
+def _connect_status_payload(record: DestinationConnectToken | None) -> dict[str, Any]:
+ if record is None:
+ return {
+ "status": DestinationConnectStatus.EXPIRED,
+ "integration_id": None,
+ "integration_kind": None,
+ "display_name": None,
+ }
+ return {
+ "status": record.status(timezone.now()),
+ "integration_id": record.integration_id,
+ "integration_kind": record.integration_kind,
+ "display_name": record.display_name,
+ }
+
+
class SyncedSourceSerializer(serializers.Serializer):
"""One source that writes to a destination. Shape only — never used to deserialize."""
@@ -473,7 +543,7 @@ class ExternalDataDestinationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewS
# access to `external_data_source` instead.
requires_resource_level_access = True
# Token auth rejects any action missing from these lists.
- scope_object_read_actions = ["list", "retrieve", "connect_link"]
+ scope_object_read_actions = ["list", "retrieve", "connect_link", "connect_link_status"]
scope_object_write_actions = [
"create",
"update",
@@ -482,6 +552,7 @@ class ExternalDataDestinationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewS
"destroy",
"add_sources",
"test_connection",
+ "connect_link_complete",
]
# `.unscoped()` is import-safe (the fail-closed manager raises on `.all()` without team
# context); the mixin scopes every request by team_id.
@@ -529,6 +600,12 @@ class ExternalDataDestinationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewS
.distinct()
)
+ def _request_user_id(self) -> int:
+ user_id = self.request.user.pk
+ if user_id is None:
+ raise NotAuthenticated()
+ return user_id
+
def _assert_can_mutate(self, instance: ExternalDataDestination) -> None:
"""Per-table gate for changing or deleting a shared destination.
@@ -567,10 +644,12 @@ class ExternalDataDestinationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewS
"""Return a secure browser link where the user connects the credentials for a destination.
The page saves an integration and does not create the destination, so secrets never pass
- through the agent. The agent then creates the destination with the new integration's id.
+ through the agent. The link carries a connect token. The agent reads the saved integration's id
+ with the token from the connect link status endpoint, then creates the destination with it.
"""
destination_type = request.validated_query_data["destination_type"]
kind = request.validated_query_data["integration_kind"]
+ connect = issue_connect_token(team_id=self.team_id, user_id=self._request_user_id(), integration_kind=kind)
target_check = (
"Creating the destination tests the connection, so a wrong target fails at that step."
if has_connection_test(destination_type)
@@ -581,21 +660,65 @@ class ExternalDataDestinationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewS
"destination_type": destination_type,
"integration_kind": kind,
"connect_url": (
- f"{settings.SITE_URL}/project/{self.team_id}/data-warehouse/connect-destination?kind={quote(kind)}"
+ f"{settings.SITE_URL}/project/{self.team_id}/data-warehouse/connect-destination"
+ f"?kind={quote(kind)}&token={quote(connect.token)}"
),
+ "connect_token": connect.token,
+ "expires_at": connect.expires_at,
"instructions": (
f"Share this link with the user. They enter their {destination_type} credentials directly in "
"PostHog. Never ask them to paste passwords, keys or tokens into the chat. The page saves the "
- "connection as an integration and shows its id. It does not create the destination. When the user "
- "says they are done, ask them for that id. If they cannot give it, call integrations-list with "
- f"kind='{kind}' and take the entry with the latest created_at (the list is oldest first), then "
- "confirm its display_name with the user. Then call external-data-destinations-create with "
- f"type='{destination_type}', a name, that integration id, and the target config that tool lists "
- f"for {destination_type}. {target_check}"
+ "connection as an integration. It does not create the destination. The user must open the link "
+ "while logged in to PostHog as the same user this session acts as. After you share the link, call "
+ "external-data-destinations-connect-link-status with this connect_token every few seconds until "
+ "status is 'connected' or 'expired'. When it is 'connected', confirm display_name with the user. "
+ "Then call external-data-destinations-create with "
+ f"type='{destination_type}', a name, the integration_id from the status, and the target config that "
+ f"tool lists for {destination_type}. {target_check} When it is 'expired', ask for a new link."
),
}
return Response(DestinationConnectLinkSerializer(data).data)
+ @validated_request(
+ request_serializer=DestinationConnectCompleteRequestSerializer,
+ responses={200: DestinationConnectStatusSerializer},
+ )
+ @action(methods=["POST"], detail=False, pagination_class=None)
+ def connect_link_complete(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
+ """Report the integration the user saved on the connect page, so the agent that sent them can read it.
+
+ The connect page calls this. Repeating the call with the same integration is safe.
+ """
+ try:
+ record = complete_connect_token(
+ team_id=self.team_id,
+ user_id=self._request_user_id(),
+ token=request.validated_data["connect_token"],
+ integration_id=request.validated_data["integration_id"],
+ )
+ except ConnectTokenNotFound:
+ raise NotFound("This connect link is unknown or has expired.")
+ except ConnectTokenOtherUser:
+ raise PermissionDenied("This connect link was created for another user.")
+ except ConnectTokenInvalidIntegration as error:
+ raise ValidationError({"integration_id": str(error)})
+ return Response(DestinationConnectStatusSerializer(_connect_status_payload(record)).data)
+
+ @validated_request(
+ query_serializer=DestinationConnectStatusQuerySerializer,
+ responses={200: DestinationConnectStatusSerializer},
+ )
+ @action(methods=["GET"], detail=False, pagination_class=None)
+ def connect_link_status(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
+ """Return whether the user saved a connection through a connect link, and which integration it is.
+
+ Never returns credentials or integration config.
+ """
+ record = read_connect_token(
+ team_id=self.team_id, user_id=self._request_user_id(), token=request.validated_query_data["connect_token"]
+ )
+ return Response(DestinationConnectStatusSerializer(_connect_status_payload(record)).data)
+
@extend_schema(request=AddSourcesRequestSerializer, responses={200: AddSourcesResponseSerializer})
@action(methods=["POST"], detail=True)
def add_sources(self, request: Request, *args: Any, **kwargs: Any) -> Response:
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_destination.py b/products/warehouse_sources/backend/tests/api/test_external_data_destination.py
index a1777c401283..d570d28e984a 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_destination.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_destination.py
@@ -1,13 +1,19 @@
import json
+from datetime import datetime, timedelta
+from urllib.parse import parse_qs, urlparse
from uuid import uuid4
import pytest
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from django.core.cache import cache
from django.db import connection
+from django.http import HttpResponse
from django.test import SimpleTestCase
from django.test.utils import CaptureQueriesContext
+from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
@@ -17,6 +23,7 @@ from rest_framework.response import Response
from posthog.constants import AvailableFeature
from posthog.models.integration import Integration
from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
+from posthog.models.team import Team
from posthog.models.user import User
from posthog.models.utils import generate_random_token_personal
@@ -36,6 +43,10 @@ from products.warehouse_sources.backend.models.external_data_destination import
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import DataWarehouseTable
+from products.warehouse_sources.backend.presentation.destination_connect_tokens import (
+ CONNECT_TOKEN_TTL,
+ issue_connect_token,
+)
from products.warehouse_sources.backend.presentation.destination_connection_check import (
FAILURE_MESSAGES,
CheckFailure,
@@ -1290,11 +1301,206 @@ class TestDestinationConnectLink(DestinationAPITestBase):
data = response.json()
assert data["destination_type"] == destination_type
assert data["integration_kind"] == kind
- assert data["connect_url"].endswith(f"/project/{self.team.pk}/data-warehouse/connect-destination?kind={kind}")
- assert f"kind='{kind}'" in data["instructions"]
+ url = urlparse(data["connect_url"])
+ assert url.path == f"/project/{self.team.pk}/data-warehouse/connect-destination"
+ assert parse_qs(url.query) == {"kind": [kind], "token": [data["connect_token"]]}
+ assert len(data["connect_token"]) >= 40
+ assert "external-data-destinations-connect-link-status" in data["instructions"]
assert f"type='{destination_type}'" in data["instructions"]
assert ("tests the connection" in data["instructions"]) == tested_on_create
+ @time_machine.travel("2026-03-01T12:00:00Z", tick=False)
+ def test_each_link_gets_its_own_token_that_expires_after_the_ttl(self) -> None:
+ first = self.client.get(f"{self.base}/connect_link?destination_type=Snowflake").json()
+ second = self.client.get(f"{self.base}/connect_link?destination_type=Snowflake").json()
+
+ assert first["connect_token"] != second["connect_token"]
+ assert datetime.fromisoformat(first["expires_at"]) == datetime.fromisoformat("2026-03-01T12:00:00+00:00") + (
+ CONNECT_TOKEN_TTL
+ )
+
+
+class TestDestinationConnectToken(DestinationAPITestBase):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+ self.integration = Integration.objects.create(
+ team=self.team,
+ kind=Integration.IntegrationKind.SNOWFLAKE,
+ integration_id="acme-account",
+ config={"account": "acme", "user": "loader", "warehouse": "wh-config-only"},
+ sensitive_config={"password": "hunter2-secret"},
+ )
+
+ def _link(self, destination_type: str = "Snowflake", **params: str) -> str:
+ query = "&".join(f"{key}={value}" for key, value in {"destination_type": destination_type, **params}.items())
+ response = self.client.get(f"{self.base}/connect_link?{query}")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ return response.json()["connect_token"]
+
+ def _complete(self, token: str, integration_id: int) -> HttpResponse:
+ return self.client.post(
+ f"{self.base}/connect_link_complete",
+ {"connect_token": token, "integration_id": integration_id},
+ format="json",
+ )
+
+ def _status(self, token: str) -> dict:
+ response = self.client.get(f"{self.base}/connect_link_status", {"connect_token": token})
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ return response.json()
+
+ def test_status_is_pending_until_the_page_reports_the_integration(self) -> None:
+ token = self._link()
+
+ assert self._status(token) == {
+ "status": "pending",
+ "integration_id": None,
+ "integration_kind": "snowflake",
+ "display_name": None,
+ }
+
+ completed = self._complete(token, self.integration.pk)
+
+ assert completed.status_code == status.HTTP_200_OK, completed.content
+ expected = {
+ "status": "connected",
+ "integration_id": self.integration.pk,
+ "integration_kind": "snowflake",
+ "display_name": self.integration.display_name,
+ }
+ assert json.loads(completed.content) == expected
+ assert self._status(token) == expected
+
+ def test_status_never_contains_integration_config_or_secrets(self) -> None:
+ token = self._link()
+ self._complete(token, self.integration.pk)
+
+ body = self.client.get(f"{self.base}/connect_link_status", {"connect_token": token}).content.decode()
+
+ for secret_or_config in ("hunter2-secret", "loader", "wh-config-only", "config"):
+ assert secret_or_config not in body
+
+ def test_s3_compatible_link_accepts_only_an_s3_compatible_integration(self) -> None:
+ token = self._link("S3", integration_kind="s3-compatible")
+ aws = self._integration(Integration.IntegrationKind.AWS_S3)
+ compatible = self._integration(Integration.IntegrationKind.S3_COMPATIBLE)
+
+ assert self._complete(token, aws.pk).status_code == status.HTTP_400_BAD_REQUEST
+ assert self._complete(token, compatible.pk).status_code == status.HTTP_200_OK
+ assert self._status(token)["integration_id"] == compatible.pk
+
+ @parameterized.expand(
+ [
+ ("wrong_kind", status.HTTP_400_BAD_REQUEST),
+ ("other_team_integration", status.HTTP_400_BAD_REQUEST),
+ ("unknown_integration", status.HTTP_400_BAD_REQUEST),
+ ("unknown_token", status.HTTP_404_NOT_FOUND),
+ ("other_team_token", status.HTTP_404_NOT_FOUND),
+ ("other_user_token", status.HTTP_403_FORBIDDEN),
+ ("expired_token", status.HTTP_404_NOT_FOUND),
+ ]
+ )
+ def test_complete_rejects(self, case: str, expected_status: int) -> None:
+ token = self._link()
+ integration_id = self.integration.pk
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ if case == "wrong_kind":
+ integration_id = self._integration(Integration.IntegrationKind.POSTGRESQL).pk
+ elif case == "other_team_integration":
+ integration_id = Integration.objects.create(
+ team=other_team, kind=Integration.IntegrationKind.SNOWFLAKE, integration_id="theirs", config={}
+ ).pk
+ elif case == "unknown_integration":
+ integration_id = 987654
+ elif case == "unknown_token":
+ token = "not-a-real-token"
+ elif case == "other_team_token":
+ token = issue_connect_token(team_id=other_team.pk, user_id=self.user.pk, integration_kind="snowflake").token
+ elif case == "other_user_token":
+ token = issue_connect_token(team_id=self.team.pk, user_id=other_user.pk, integration_kind="snowflake").token
+
+ if case == "expired_token":
+ with time_machine.travel(timezone.now() + CONNECT_TOKEN_TTL + timedelta(seconds=1), tick=False):
+ response = self._complete(token, integration_id)
+ else:
+ response = self._complete(token, integration_id)
+
+ assert response.status_code == expected_status, response.content
+ if case in ("other_team_token", "other_user_token"):
+ return
+ assert self._status(token)["status"] in ("pending", "expired")
+ assert self._status(token)["integration_id"] is None
+
+ def test_complete_is_idempotent_and_does_not_switch_integrations(self) -> None:
+ token = self._link()
+ other = Integration.objects.create(
+ team=self.team, kind=Integration.IntegrationKind.SNOWFLAKE, integration_id="other-account", config={}
+ )
+
+ first = self._complete(token, self.integration.pk)
+ repeat = self._complete(token, self.integration.pk)
+ switch = self._complete(token, other.pk)
+
+ assert first.status_code == repeat.status_code == status.HTTP_200_OK
+ assert json.loads(repeat.content) == json.loads(first.content)
+ assert switch.status_code == status.HTTP_400_BAD_REQUEST
+ assert self._status(token)["integration_id"] == self.integration.pk
+
+ def test_concurrent_completions_with_different_integrations_keep_the_first(self) -> None:
+ token = self._link()
+ other = Integration.objects.create(
+ team=self.team, kind=Integration.IntegrationKind.SNOWFLAKE, integration_id="other-account", config={}
+ )
+ record_key = f"wh_dest_connect:{self.team.pk}:{token}"
+ pending = cache.get(record_key)
+
+ first = self._complete(token, other.pk)
+ # The second tab read the token before the first save landed, so it still sees it pending.
+ cache.set(record_key, pending)
+ second = self._complete(token, self.integration.pk)
+
+ assert first.status_code == status.HTTP_200_OK, first.content
+ assert second.status_code == status.HTTP_400_BAD_REQUEST, second.content
+ assert self._status(token)["integration_id"] is None
+
+ @parameterized.expand([("unknown",), ("other_user",), ("other_team",), ("evicted",)])
+ def test_status_of_a_token_the_user_cannot_read_is_expired(self, case: str) -> None:
+ token = self._link()
+ if case == "unknown":
+ token = "not-a-real-token"
+ elif case == "other_user":
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ token = issue_connect_token(team_id=self.team.pk, user_id=other_user.pk, integration_kind="snowflake").token
+ elif case == "other_team":
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ token = issue_connect_token(team_id=other_team.pk, user_id=self.user.pk, integration_kind="snowflake").token
+ else:
+ cache.clear()
+
+ assert self._status(token) == {
+ "status": "expired",
+ "integration_id": None,
+ "integration_kind": None,
+ "display_name": None,
+ }
+
+ def test_status_expires_while_pending_but_a_connection_outlives_the_link(self) -> None:
+ pending_token = self._link()
+ connected_token = self._link()
+ with time_machine.travel(timezone.now() + CONNECT_TOKEN_TTL - timedelta(minutes=1), tick=False):
+ assert self._complete(connected_token, self.integration.pk).status_code == status.HTTP_200_OK
+
+ with time_machine.travel(timezone.now() + CONNECT_TOKEN_TTL + timedelta(minutes=1), tick=False):
+ assert self._status(pending_token)["status"] == "expired"
+ assert self._status(connected_token)["status"] == "connected"
+
+ def test_status_needs_a_token(self) -> None:
+ response = self.client.get(f"{self.base}/connect_link_status")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
class TestDestinationAPIKeyScopes(DestinationAPITestBase):
def setUp(self) -> None:
@@ -1309,6 +1515,10 @@ class TestDestinationAPIKeyScopes(DestinationAPITestBase):
@parameterized.expand(
[
("external_data_source:read", "GET", "connect_link?destination_type=Postgres", status.HTTP_200_OK),
+ ("external_data_source:read", "GET", "connect_link_status?connect_token=unknown", status.HTTP_200_OK),
+ ("external_data_source:read", "POST", "connect_link_complete", status.HTTP_403_FORBIDDEN),
+ # The write scope passes, then the body (which has no token) fails validation.
+ ("external_data_source:write", "POST", "connect_link_complete", status.HTTP_400_BAD_REQUEST),
("external_data_source:read", "POST", "{destination}/add_sources", status.HTTP_403_FORBIDDEN),
("external_data_source:write", "POST", "{destination}/add_sources", status.HTTP_200_OK),
("external_data_source:read", "POST", "{destination}/test_connection", status.HTTP_403_FORBIDDEN),
diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.ts
index 6ad95409942e..382a98f3959d 100644
--- a/products/warehouse_sources/frontend/generated/api.schemas.ts
+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts
@@ -253,10 +253,65 @@ export interface DestinationConnectLinkApi {
integration_kind: string
/** Full URL to share with the user. It opens the connection form for this integration kind in PostHog, so credentials never pass through the agent or the chat. */
connect_url: string
+ /** Secret token in the link. Pass it to the connect link status endpoint to learn which integration the user saved. Only the user who asked for the link can read its status. */
+ connect_token: string
+ /** When the link stops accepting a new connection. Ask for a new link after this time. */
+ expires_at: string
/** Next steps for the agent to relay to the user. */
instructions: string
}
+export interface DestinationConnectCompleteRequestApi {
+ /**
+ * The connect token from the connect link URL.
+ * @maxLength 128
+ */
+ connect_token: string
+ /**
+ * Id of the integration the user saved on the connect page.
+ * @minimum 1
+ */
+ integration_id: number
+}
+
+/**
+ * * `pending` - Pending
+ * * `connected` - Connected
+ * * `expired` - Expired
+ */
+export type DestinationConnectStatusEnumApi =
+ (typeof DestinationConnectStatusEnumApi)[keyof typeof DestinationConnectStatusEnumApi]
+
+export const DestinationConnectStatusEnumApi = {
+ Pending: 'pending',
+ Connected: 'connected',
+ Expired: 'expired',
+} as const
+
+export interface DestinationConnectStatusApi {
+ /** `pending`: the user has not saved a connection yet. `connected`: the user saved one, and integration_id holds it. `expired`: the link is no longer valid, or it is unknown or belongs to another user. Ask for a new link.
+ *
+ * * `pending` - Pending
+ * * `connected` - Connected
+ * * `expired` - Expired */
+ status: DestinationConnectStatusEnumApi
+ /**
+ * Id of the saved integration when status is `connected`. Pass it to destination create.
+ * @nullable
+ */
+ integration_id: number | null
+ /**
+ * The integration kind the link is for. Null when status is `expired`.
+ * @nullable
+ */
+ integration_kind: string | null
+ /**
+ * Name of the saved connection, such as the account or host, to confirm with the user.
+ * @nullable
+ */
+ display_name: string | null
+}
+
/**
* * `full_refresh` - full_refresh
* * `incremental` - incremental
@@ -2251,6 +2306,15 @@ export const ExternalDataDestinationsConnectLinkRetrieveDestinationType = {
S3: 'S3',
} as const
+export type ExternalDataDestinationsConnectLinkStatusRetrieveParams = {
+ /**
+ * The connect_token that the connect link returned.
+ * @minLength 1
+ * @maxLength 128
+ */
+ connect_token: string
+}
+
export type ExternalDataSchemasListParams = {
/**
* Number of results to return per page.
diff --git a/products/warehouse_sources/frontend/generated/api.ts b/products/warehouse_sources/frontend/generated/api.ts
index 4ae20df14117..9ea7656e464c 100644
--- a/products/warehouse_sources/frontend/generated/api.ts
+++ b/products/warehouse_sources/frontend/generated/api.ts
@@ -18,13 +18,16 @@ import type {
CredentialAccountsRequestApi,
DatabaseSchemaRequestApi,
DeleteWebhookResponseApi,
+ DestinationConnectCompleteRequestApi,
DestinationConnectLinkApi,
+ DestinationConnectStatusApi,
DestinationConnectionTestResponseApi,
DirectConnectionSourceOptionApi,
DraftCustomManifestRequestApi,
DraftCustomManifestResponseApi,
ExternalDataDestinationApi,
ExternalDataDestinationsConnectLinkRetrieveParams,
+ ExternalDataDestinationsConnectLinkStatusRetrieveParams,
ExternalDataDestinationsListParams,
ExternalDataJobSerializersApi,
ExternalDataSchemaApi,
@@ -305,7 +308,8 @@ export const getExternalDataDestinationsConnectLinkRetrieveUrl = (
* Return a secure browser link where the user connects the credentials for a destination.
*
* The page saves an integration and does not create the destination, so secrets never pass
- * through the agent. The agent then creates the destination with the new integration's id.
+ * through the agent. The link carries a connect token. The agent reads the saved integration's id
+ * with the token from the connect link status endpoint, then creates the destination with it.
*/
export const externalDataDestinationsConnectLinkRetrieve = async (
projectId: string,
@@ -318,6 +322,66 @@ export const externalDataDestinationsConnectLinkRetrieve = async (
})
}
+export const getExternalDataDestinationsConnectLinkCompleteCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/external_data_destinations/connect_link_complete/`
+}
+
+/**
+ * Report the integration the user saved on the connect page, so the agent that sent them can read it.
+ *
+ * The connect page calls this. Repeating the call with the same integration is safe.
+ */
+export const externalDataDestinationsConnectLinkCompleteCreate = async (
+ projectId: string,
+ destinationConnectCompleteRequestApi: DestinationConnectCompleteRequestApi,
+ options?: RequestInit
+): Promise<DestinationConnectStatusApi> => {
+ return apiMutator<DestinationConnectStatusApi>(getExternalDataDestinationsConnectLinkCompleteCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(destinationConnectCompleteRequestApi),
+ })
+}
+
+export const getExternalDataDestinationsConnectLinkStatusRetrieveUrl = (
+ projectId: string,
+ params: ExternalDataDestinationsConnectLinkStatusRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/external_data_destinations/connect_link_status/?${stringifiedParams}`
+ : `/api/projects/${projectId}/external_data_destinations/connect_link_status/`
+}
+
+/**
+ * Return whether the user saved a connection through a connect link, and which integration it is.
+ *
+ * Never returns credentials or integration config.
+ */
+export const externalDataDestinationsConnectLinkStatusRetrieve = async (
+ projectId: string,
+ params: ExternalDataDestinationsConnectLinkStatusRetrieveParams,
+ options?: RequestInit
+): Promise<DestinationConnectStatusApi> => {
+ return apiMutator<DestinationConnectStatusApi>(
+ getExternalDataDestinationsConnectLinkStatusRetrieveUrl(projectId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
export const getExternalDataSchemasListUrl = (projectId: string, params?: ExternalDataSchemasListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/warehouse_sources/frontend/generated/api.zod.ts b/products/warehouse_sources/frontend/generated/api.zod.ts
index 85a54661a74f..f1ce05ccc461 100644
--- a/products/warehouse_sources/frontend/generated/api.zod.ts
+++ b/products/warehouse_sources/frontend/generated/api.zod.ts
@@ -137,6 +137,21 @@ export const ExternalDataDestinationsAddSourcesCreateBody = /* @__PURE__ */ zod.
.describe('Start a full resync for each enabled table newly attached.'),
})
+/**
+ * Report the integration the user saved on the connect page, so the agent that sent them can read it.
+ *
+ * The connect page calls this. Repeating the call with the same integration is safe.
+ */
+export const externalDataDestinationsConnectLinkCompleteCreateBodyConnectTokenMax = 128
+
+export const ExternalDataDestinationsConnectLinkCompleteCreateBody = /* @__PURE__ */ zod.object({
+ connect_token: zod
+ .string()
+ .max(externalDataDestinationsConnectLinkCompleteCreateBodyConnectTokenMax)
+ .describe('The connect token from the connect link URL.'),
+ integration_id: zod.number().min(1).describe('Id of the integration the user saved on the connect page.'),
+})
+
export const externalDataSchemasUpdateBodyIncrementalFieldLookbackSecondsMin = 0
export const externalDataSchemasUpdateBodyIncrementalFieldLookbackSecondsMax = 5184000
diff --git a/products/warehouse_sources/mcp/warehouse_destinations.yaml b/products/warehouse_sources/mcp/warehouse_destinations.yaml
index 7512733e024c..29c74453804c 100644
--- a/products/warehouse_sources/mcp/warehouse_destinations.yaml
+++ b/products/warehouse_sources/mcp/warehouse_destinations.yaml
@@ -44,13 +44,39 @@ tools:
annotations:
readOnly: true
destructive: false
- idempotent: true
+ idempotent: false
title: Get a secure connect link for a destination
description: >
First step to add a warehouse destination (Postgres, Redshift, Snowflake, BigQuery, Databricks, S3 or Azure
- Blob). Returns a browser link where the user enters the credentials in PostHog, plus the next steps in
- `instructions`. For S3-compatible storage (MinIO, Wasabi, R2, GCS), pass integration_kind='s3-compatible'.
- Never ask the user to paste passwords, keys or tokens into the chat.
+ Blob). Returns a browser link where the user enters the credentials in PostHog, a connect_token, and the
+ next steps in `instructions`. For S3-compatible storage (MinIO, Wasabi, R2, GCS), pass
+ integration_kind='s3-compatible'. After you share the link, poll
+ external-data-destinations-connect-link-status with the connect_token to get the saved integration id. Never
+ ask the user to paste passwords, keys or tokens into the chat.
+ feature_flag: warehouse-multi-destination
+ external-data-destinations-connect-link-complete:
+ operation: external_data_destinations_connect_link_complete_create
+ enabled: false
+ disabled_reason:
+ The connect page in the browser calls this after the user saves the connection. Agents read the result
+ with external-data-destinations-connect-link-status.
+ external-data-destinations-connect-link-status:
+ operation: external_data_destinations_connect_link_status_retrieve
+ enabled: true
+ scopes:
+ - external_data_source:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Check a destination connect link
+ description: >
+ Read whether the user saved a connection through a link from external-data-destinations-connect-link. Pass
+ the connect_token from that call. After you give the user the link, call this every few seconds until status
+ is 'connected' or 'expired'. 'pending' means the user has not saved yet. 'connected' returns integration_id
+ and display_name: confirm display_name with the user, then pass integration_id to
+ external-data-destinations-create. 'expired' means the link is too old or was made for another user: get a
+ new link. Never returns credentials.
feature_flag: warehouse-multi-destination
external-data-destinations-create:
operation: external_data_destinations_create
diff --git a/products/warehouse_sources/skills/setting-up-a-data-warehouse-source/SKILL.md b/products/warehouse_sources/skills/setting-up-a-data-warehouse-source/SKILL.md
index a5d56edea3d9..b44eb1d0efdc 100644
--- a/products/warehouse_sources/skills/setting-up-a-data-warehouse-source/SKILL.md
+++ b/products/warehouse_sources/skills/setting-up-a-data-warehouse-source/SKILL.md
@@ -43,6 +43,7 @@ hand-pick which tables sync or set non-default sync types per table.
| `external-data-schemas-list` | See per-table sync status once the source is created |
| `external-data-destinations-list` | See existing destinations, including the PostHog warehouse |
| `external-data-destinations-connect-link` | Secure browser link where the user enters a destination's credentials; returns nothing secret |
+| `external-data-destinations-connect-link-status` | Poll with the link's `connect_token` to get the integration the user saved |
| `external-data-destinations-create` | Create a destination from the integration the connect page saved |
| `external-data-destinations-add-sources` | Attach existing sources to a destination |
| `external-data-sources-destinations-update` | Set a source's full destination list, for example to keep the PostHog warehouse before attaching |
@@ -343,11 +344,12 @@ Azure Blob storage. These tools exist only when the feature is on for the projec
1. Call `external-data-destinations-list` first. If a destination for that target already exists, reuse it, but only
when its `status` is `healthy`. A `failing` or `paused` one needs fixing first (see the end of this section).
2. Call `external-data-destinations-connect-link` with the `destination_type` (for S3-compatible storage such as R2 or
- MinIO, also pass `integration_kind: "s3-compatible"`). Share `connect_url` and wait until the user says they are
- done. The page saves an integration and shows its id.
-3. Ask the user for the id the page showed. If they cannot give it, call `integrations-list` with the returned
- `integration_kind` and take the entry with the latest `created_at` (the list is oldest first). Confirm its
- `display_name` with the user before you use it.
+ MinIO, also pass `integration_kind: "s3-compatible"`). Share `connect_url`. The user must open it while logged in
+ to PostHog as the same user this session acts as. The page saves an integration.
+3. Call `external-data-destinations-connect-link-status` with the returned `connect_token` every few seconds until
+ `status` is `connected` or `expired`. When it is `connected`, confirm `display_name` with the user and use
+ `integration_id`. When it is `expired`, get a new link. If the user saved the connection as another PostHog user,
+ the page shows the integration id instead: ask the user for it.
4. Ask the user for the target (database and schema, dataset, bucket and prefix, and so on), then call
`external-data-destinations-create` with `type`, `name`, `integration` and `config`. Creation tests the
connection for every type except Redshift, and a 400 names the field to fix. A wrong Redshift target only shows up
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 51ad2d7d3afd..f27fe63bcda9 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -6330,13 +6330,29 @@
"feature_flag": "warehouse-multi-destination"
},
"external-data-destinations-connect-link": {
- "description": "First step to add a warehouse destination (Postgres, Redshift, Snowflake, BigQuery, Databricks, S3 or Azure Blob). Returns a browser link where the user enters the credentials in PostHog, plus the next steps in `instructions`. For S3-compatible storage (MinIO, Wasabi, R2, GCS), pass integration_kind='s3-compatible'. Never ask the user to paste passwords, keys or tokens into the chat.",
+ "description": "First step to add a warehouse destination (Postgres, Redshift, Snowflake, BigQuery, Databricks, S3 or Azure Blob). Returns a browser link where the user enters the credentials in PostHog, a connect_token, and the next steps in `instructions`. For S3-compatible storage (MinIO, Wasabi, R2, GCS), pass integration_kind='s3-compatible'. After you share the link, poll external-data-destinations-connect-link-status with the connect_token to get the saved integration id. Never ask the user to paste passwords, keys or tokens into the chat.",
"category": "Warehouse destinations",
"feature": "warehouse_sources",
"summary": "Get a secure connect link for a destination",
"title": "Get a secure connect link for a destination",
"required_scopes": ["external_data_source:read"],
"api_operations": ["GET /api/projects/{project_id}/external_data_destinations/connect_link/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "warehouse-multi-destination"
+ },
+ "external-data-destinations-connect-link-status": {
+ "description": "Read whether the user saved a connection through a link from external-data-destinations-connect-link. Pass the connect_token from that call. After you give the user the link, call this every few seconds until status is 'connected' or 'expired'. 'pending' means the user has not saved yet. 'connected' returns integration_id and display_name: confirm display_name with the user, then pass integration_id to external-data-destinations-create. 'expired' means the link is too old or was made for another user: get a new link. Never returns credentials.",
+ "category": "Warehouse destinations",
+ "feature": "warehouse_sources",
+ "summary": "Check a destination connect link",
+ "title": "Check a destination connect link",
+ "required_scopes": ["external_data_source:read"],
+ "api_operations": ["GET /api/projects/{project_id}/external_data_destinations/connect_link_status/"],
"annotations": {
"destructiveHint": false,
"idempotentHint": true,
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 6eedaa13a683..91705934fe08 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6463,13 +6463,29 @@
"feature_flag": "warehouse-multi-destination"
},
"external-data-destinations-connect-link": {
- "description": "First step to add a warehouse destination (Postgres, Redshift, Snowflake, BigQuery, Databricks, S3 or Azure Blob). Returns a browser link where the user enters the credentials in PostHog, plus the next steps in `instructions`. For S3-compatible storage (MinIO, Wasabi, R2, GCS), pass integration_kind='s3-compatible'. Never ask the user to paste passwords, keys or tokens into the chat.",
+ "description": "First step to add a warehouse destination (Postgres, Redshift, Snowflake, BigQuery, Databricks, S3 or Azure Blob). Returns a browser link where the user enters the credentials in PostHog, a connect_token, and the next steps in `instructions`. For S3-compatible storage (MinIO, Wasabi, R2, GCS), pass integration_kind='s3-compatible'. After you share the link, poll external-data-destinations-connect-link-status with the connect_token to get the saved integration id. Never ask the user to paste passwords, keys or tokens into the chat.",
"category": "Warehouse destinations",
"feature": "warehouse_sources",
"summary": "Get a secure connect link for a destination",
"title": "Get a secure connect link for a destination",
"required_scopes": ["external_data_source:read"],
"api_operations": ["GET /api/projects/{project_id}/external_data_destinations/connect_link/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "warehouse-multi-destination"
+ },
+ "external-data-destinations-connect-link-status": {
+ "description": "Read whether the user saved a connection through a link from external-data-destinations-connect-link. Pass the connect_token from that call. After you give the user the link, call this every few seconds until status is 'connected' or 'expired'. 'pending' means the user has not saved yet. 'connected' returns integration_id and display_name: confirm display_name with the user, then pass integration_id to external-data-destinations-create. 'expired' means the link is too old or was made for another user: get a new link. Never returns credentials.",
+ "category": "Warehouse destinations",
+ "feature": "warehouse_sources",
+ "summary": "Check a destination connect link",
+ "title": "Check a destination connect link",
+ "required_scopes": ["external_data_source:read"],
+ "api_operations": ["GET /api/projects/{project_id}/external_data_destinations/connect_link_status/"],
"annotations": {
"destructiveHint": false,
"idempotentHint": true,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f1b8651f78a2..3488427ab783 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -34451,6 +34451,19 @@ export namespace Schemas {
response_id: string;
}
+ export interface DestinationConnectCompleteRequest {
+ /**
+ * The connect token from the connect link URL.
+ * @maxLength 128
+ */
+ connect_token: string;
+ /**
+ * Id of the integration the user saved on the connect page.
+ * @minimum 1
+ */
+ integration_id: number;
+ }
+
export interface DestinationConnectLink {
/** The destination type the link is for. */
destination_type: string;
@@ -34458,10 +34471,52 @@ export namespace Schemas {
integration_kind: string;
/** Full URL to share with the user. It opens the connection form for this integration kind in PostHog, so credentials never pass through the agent or the chat. */
connect_url: string;
+ /** Secret token in the link. Pass it to the connect link status endpoint to learn which integration the user saved. Only the user who asked for the link can read its status. */
+ connect_token: string;
+ /** When the link stops accepting a new connection. Ask for a new link after this time. */
+ expires_at: string;
/** Next steps for the agent to relay to the user. */
instructions: string;
}
+ /**
+ * * `pending` - Pending
+ * * `connected` - Connected
+ * * `expired` - Expired
+ */
+ export type DestinationConnectStatusEnum = typeof DestinationConnectStatusEnum[keyof typeof DestinationConnectStatusEnum];
+
+
+ export const DestinationConnectStatusEnum = {
+ Pending: 'pending',
+ Connected: 'connected',
+ Expired: 'expired',
+ } as const;
+
+ export interface DestinationConnectStatus {
+ /** `pending`: the user has not saved a connection yet. `connected`: the user saved one, and integration_id holds it. `expired`: the link is no longer valid, or it is unknown or belongs to another user. Ask for a new link.
+ *
+ * * `pending` - Pending
+ * * `connected` - Connected
+ * * `expired` - Expired */
+ status: DestinationConnectStatusEnum;
+ /**
+ * Id of the saved integration when status is `connected`. Pass it to destination create.
+ * @nullable
+ */
+ integration_id: number | null;
+ /**
+ * The integration kind the link is for. Null when status is `expired`.
+ * @nullable
+ */
+ integration_kind: string | null;
+ /**
+ * Name of the saved connection, such as the account or host, to confirm with the user.
+ * @nullable
+ */
+ display_name: string | null;
+ }
+
/**
* * `Passed` - Passed
* * `Failed` - Failed
@@ -125362,6 +125417,15 @@ export namespace Schemas {
S3: 'S3',
} as const;
+ export type ExternalDataDestinationsConnectLinkStatusRetrieveParams = {
+ /**
+ * The connect_token that the connect link returned.
+ * @minLength 1
+ * @maxLength 128
+ */
+ connect_token: string;
+ };
+
export type ExternalDataSchemasListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/warehouse_destinations/api.ts b/services/mcp/src/generated/warehouse_destinations/api.ts
index 0c53404391ed..d5e2e265890f 100644
--- a/services/mcp/src/generated/warehouse_destinations/api.ts
+++ b/services/mcp/src/generated/warehouse_destinations/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 6 enabled ops
+ * PostHog API - MCP 7 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -131,7 +131,8 @@ export const ExternalDataDestinationsTestConnectionCreateParams = () => zod.obje
* Return a secure browser link where the user connects the credentials for a destination.
*
* The page saves an integration and does not create the destination, so secrets never pass
- * through the agent. The agent then creates the destination with the new integration's id.
+ * through the agent. The link carries a connect token. The agent reads the saved integration's id
+ * with the token from the connect link status endpoint, then creates the destination with it.
*/
export const ExternalDataDestinationsConnectLinkRetrieveParams = () => zod.object({
project_id: zod
@@ -155,3 +156,26 @@ export const ExternalDataDestinationsConnectLinkRetrieveQueryParams = () => zod.
"Which integration kind to connect when the type accepts more than one. Only S3 does: 'aws-s3' (the default) or 's3-compatible' for MinIO, Wasabi, R2, GCS and similar."
),
})
+
+/**
+ * Return whether the user saved a connection through a connect link, and which integration it is.
+ *
+ * Never returns credentials or integration config.
+ */
+export const ExternalDataDestinationsConnectLinkStatusRetrieveParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const externalDataDestinationsConnectLinkStatusRetrieveQueryConnectTokenMax = 128
+
+export const ExternalDataDestinationsConnectLinkStatusRetrieveQueryParams = () => zod.object({
+ connect_token: zod
+ .string()
+ .min(1)
+ .max(externalDataDestinationsConnectLinkStatusRetrieveQueryConnectTokenMax)
+ .describe('The connect_token that the connect link returned.'),
+})
diff --git a/services/mcp/src/tools/generated/warehouse_destinations.ts b/services/mcp/src/tools/generated/warehouse_destinations.ts
index 0110514f7906..4c5b5156a617 100644
--- a/services/mcp/src/tools/generated/warehouse_destinations.ts
+++ b/services/mcp/src/tools/generated/warehouse_destinations.ts
@@ -67,6 +67,34 @@ const externalDataDestinationsConnectLink = (): ToolBase<
},
})
+const ExternalDataDestinationsConnectLinkStatusSchema = () => {
+ const ExternalDataDestinationsConnectLinkStatusRetrieveQueryParams =
+ orvalSchemas.ExternalDataDestinationsConnectLinkStatusRetrieveQueryParams()
+ return ExternalDataDestinationsConnectLinkStatusRetrieveQueryParams
+}
+
+const externalDataDestinationsConnectLinkStatus = (): ToolBase<
+ ReturnType<typeof ExternalDataDestinationsConnectLinkStatusSchema>,
+ Schemas.DestinationConnectStatus
+> => ({
+ name: 'external-data-destinations-connect-link-status',
+ schema: ExternalDataDestinationsConnectLinkStatusSchema(),
+ handler: async (
+ context: Context,
+ params: z.infer<ReturnType<typeof ExternalDataDestinationsConnectLinkStatusSchema>>
+ ) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.DestinationConnectStatus>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_destinations/connect_link_status/`,
+ query: {
+ connect_token: params.connect_token,
+ },
+ })
+ return result
+ },
+})
+
const ExternalDataDestinationsCreateSchema = () => {
const ExternalDataDestinationsCreateBody = orvalSchemas.ExternalDataDestinationsCreateBody()
return ExternalDataDestinationsCreateBody
@@ -176,6 +204,7 @@ const externalDataDestinationsTestConnection = (): ToolBase<
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'external-data-destinations-add-sources': externalDataDestinationsAddSources,
'external-data-destinations-connect-link': externalDataDestinationsConnectLink,
+ 'external-data-destinations-connect-link-status': externalDataDestinationsConnectLinkStatus,
'external-data-destinations-create': externalDataDestinationsCreate,
'external-data-destinations-list': externalDataDestinationsList,
'external-data-destinations-retrieve': externalDataDestinationsRetrieve,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-destinations-connect-link-status.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-destinations-connect-link-status.json
new file mode 100644
index 000000000000..830baca15af7
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-destinations-connect-link-status.json
@@ -0,0 +1,13 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "connect_token": {
+ "description": "The connect_token that the connect link returned.",
+ "maxLength": 128,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": ["connect_token"],
+ "type": "object"
+}