Skip to content

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

feat(data-warehouse): let the create endpoint use a stored credential_id (#71056)

Tom Owers061e90d2f430
diff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.py
index 647705dbb074..87151406d9da 100644
--- a/products/data_warehouse/backend/presentation/views/external_data_source.py
+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py
@@ -1802,24 +1802,79 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
)
@extend_schema(request=ExternalDataSourceCreateSerializer, responses=ExternalDataSourceSerializers)
+ def _resolve_stored_credential(
+ self, source_type: str, payload: dict
+ ) -> tuple[dict, PendingSourceCredential | None, Response | None]:
+ """Merge a connect-link stored credential into `payload` when it carries a `credential_id`.
+
+ Lets the create and setup flows reference credentials the user entered on the connect page
+ instead of passing secrets inline. Returns the (possibly merged) payload, the resolved
+ credential (which the caller deletes once consumed — stored credentials are single-use), and
+ a 400 Response to return as-is on a lookup miss or source-type mismatch.
+ """
+ credential_id = payload.pop("credential_id", None)
+ if credential_id is None:
+ return payload, None, None
+ try:
+ credential = PendingSourceCredential.objects.for_team(self.team_id).get(
+ id=credential_id, expires_at__gt=timezone.now()
+ )
+ except (PendingSourceCredential.DoesNotExist, ValueError, TypeError, DjangoValidationError):
+ return (
+ payload,
+ None,
+ Response(
+ status=status.HTTP_400_BAD_REQUEST,
+ data={"message": f"Stored credential '{credential_id}' not found or expired"},
+ ),
+ )
+ if credential.source_type != source_type:
+ return (
+ payload,
+ None,
+ Response(
+ status=status.HTTP_400_BAD_REQUEST,
+ data={
+ "message": f"Stored credential '{credential_id}' is for "
+ f"'{credential.source_type}', not '{source_type}'"
+ },
+ ),
+ )
+ # Stored credentials win over inline keys so an agent can't override what the user entered.
+ return {**payload, **credential.payload}, credential, None
+
def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
- secret_ref_response = _unresolved_secret_ref_response(serializer.validated_data["payload"])
+ source_type = serializer.validated_data["source_type"]
+ payload = dict(serializer.validated_data["payload"] or {})
+
+ secret_ref_response = _unresolved_secret_ref_response(payload)
if secret_ref_response is not None:
return secret_ref_response
- return self._create_external_data_source(
+ # A `credential_id` in the payload references connection details the user entered on the
+ # connect-link page — resolve it to the real secrets so `create` can target a specific
+ # `schemas` set (unlike `setup`, which discovers and enables every table).
+ payload, credential, credential_error = self._resolve_stored_credential(source_type, payload)
+ if credential_error is not None:
+ return credential_error
+
+ response = self._create_external_data_source(
request,
- source_type=serializer.validated_data["source_type"],
- payload=serializer.validated_data["payload"],
+ source_type=source_type,
+ payload=payload,
prefix=serializer.validated_data.get("prefix"),
description=serializer.validated_data.get("description"),
access_method=serializer.validated_data.get("access_method", ExternalDataSource.AccessMethod.WAREHOUSE),
created_via=serializer.validated_data.get("created_via", ExternalDataSource.CreatedVia.API),
direct_query_enabled=serializer.validated_data.get("direct_query_enabled", False),
)
+ # Stored credentials are single-use: once the source owns them (in job_inputs), drop the stash.
+ if credential is not None and response.status_code == status.HTTP_201_CREATED:
+ credential.delete()
+ return response
@extend_schema(
parameters=[
@@ -3082,28 +3137,9 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
if secret_ref_response is not None:
return secret_ref_response
- credential: PendingSourceCredential | None = None
- credential_id = payload.pop("credential_id", None)
- if credential_id is not None:
- try:
- credential = PendingSourceCredential.objects.for_team(self.team_id).get(
- id=credential_id, expires_at__gt=timezone.now()
- )
- except (PendingSourceCredential.DoesNotExist, ValueError, TypeError, DjangoValidationError):
- return Response(
- status=status.HTTP_400_BAD_REQUEST,
- data={"message": f"Stored credential '{credential_id}' not found or expired"},
- )
- if credential.source_type != source_type:
- return Response(
- status=status.HTTP_400_BAD_REQUEST,
- data={
- "message": f"Stored credential '{credential_id}' is for "
- f"'{credential.source_type}', not '{source_type}'"
- },
- )
- # Stored credentials win over inline keys so an agent can't override what the user entered.
- payload = {**payload, **credential.payload}
+ payload, credential, credential_error = self._resolve_stored_credential(source_type, payload)
+ if credential_error is not None:
+ return credential_error
source_type_model = ExternalDataSourceType(source_type)
source = SourceRegistry.get_source(source_type_model)
diff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.py
index 510d21253414..23f8a0720839 100644
--- a/products/data_warehouse/backend/tests/api/test_external_data_source.py
+++ b/products/data_warehouse/backend/tests/api/test_external_data_source.py
@@ -10796,6 +10796,61 @@ class TestExternalDataSourceSetup(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "is for 'Stripe'" in response.json()["message"]
+ @patch("products.data_warehouse.backend.presentation.views.external_data_source.ensure_person_join")
+ @patch("products.data_modeling.backend.models.datawarehouse_managed_viewset.DataWarehouseManagedViewSet.sync_views")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",
+ return_value=(True, None),
+ )
+ def test_create_with_stored_credential_targets_only_requested_schemas_and_consumes_it(
+ self, mock_validate, _mock_sync_views, _mock_person_join
+ ):
+ credential = self._store_stripe_credential()
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/",
+ data={
+ "source_type": "Stripe",
+ "payload": {
+ "credential_id": str(credential.pk),
+ "schemas": [
+ {"name": STRIPE_CUSTOMER_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},
+ ],
+ },
+ },
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+
+ source = ExternalDataSource.objects.get(pk=response.json()["id"])
+ # The stored secret was merged in server-side and used for validation.
+ assert mock_validate.call_args.args[0].auth_method.stripe_secret_key == "sk_test_stored"
+ # Unlike setup, create honors the caller's schemas: only the requested table syncs.
+ should_sync = {s.name: s.should_sync for s in ExternalDataSchema.objects.filter(source_id=source.pk)}
+ assert should_sync.get(STRIPE_CUSTOMER_RESOURCE_NAME) is True
+ assert should_sync.get(STRIPE_SUBSCRIPTION_RESOURCE_NAME) in (False, None)
+ # Stored credentials are single-use — consumed on successful create.
+ assert not PendingSourceCredential.objects.for_team(self.team.pk).exists()
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",
+ return_value=(False, "Invalid Stripe API key"),
+ )
+ def test_create_with_stored_credential_failure_keeps_it(self, _mock_validate):
+ credential = self._store_stripe_credential()
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/",
+ data={
+ "source_type": "Stripe",
+ "payload": {
+ "credential_id": str(credential.pk),
+ "schemas": [
+ {"name": STRIPE_CUSTOMER_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},
+ ],
+ },
+ },
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert PendingSourceCredential.objects.for_team(self.team.pk).filter(pk=credential.pk).exists()
+
class TestExternalDataSourceStoreCredentials(APIBaseTest):
def _store(self, source_type: str = "Stripe", payload: dict | None = None):
diff --git a/products/warehouse_sources/frontend/generated/api.ts b/products/warehouse_sources/frontend/generated/api.ts
index cc46ba2aa9b1..db5f937520ec 100644
--- a/products/warehouse_sources/frontend/generated/api.ts
+++ b/products/warehouse_sources/frontend/generated/api.ts
@@ -326,8 +326,8 @@ export const externalDataSourcesCreate = async (
projectId: string,
externalDataSourceCreateApi: ExternalDataSourceCreateApi,
options?: RequestInit
-): Promise<ExternalDataSourceSerializersApi> => {
- return apiMutator<ExternalDataSourceSerializersApi>(getExternalDataSourcesCreateUrl(projectId), {
+): Promise<ExternalDataSourceCreateApi> => {
+ return apiMutator<ExternalDataSourceCreateApi>(getExternalDataSourcesCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
diff --git a/services/mcp/src/tools/generated/warehouse_sources.ts b/services/mcp/src/tools/generated/warehouse_sources.ts
index ae3516c2446a..01d235361e7a 100644
--- a/services/mcp/src/tools/generated/warehouse_sources.ts
+++ b/services/mcp/src/tools/generated/warehouse_sources.ts
@@ -468,7 +468,7 @@ const ExternalDataSourcesCreateSchema = ExternalDataSourcesCreateBody.extend({
const externalDataSourcesCreate = (): ToolBase<
typeof ExternalDataSourcesCreateSchema,
- Schemas.ExternalDataSourceSerializers
+ Schemas.ExternalDataSourceCreate
> => ({
name: 'external-data-sources-create',
schema: ExternalDataSourcesCreateSchema,
@@ -494,7 +494,7 @@ const externalDataSourcesCreate = (): ToolBase<
body['direct_query_enabled'] = params.direct_query_enabled
}
body['created_via'] = 'mcp'
- const result = await context.api.request<Schemas.ExternalDataSourceSerializers>({
+ const result = await context.api.request<Schemas.ExternalDataSourceCreate>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_sources/`,
body,