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.

fix(data-warehouse): scope pending source credentials to their creator (#71250)

Daniel RC8d699fc23a72
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 90e4d63ca8b7..f943df559c76 100644
--- a/products/data_warehouse/backend/presentation/views/external_data_source.py
+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py
@@ -1463,6 +1463,10 @@ class SourceSetupResponseSerializer(serializers.Serializer):
)
+class ExternalDataSourceCreateResponseSerializer(serializers.Serializer):
+ id = serializers.UUIDField(help_text="ID of the created external data source.")
+
+
class SourceConnectLinkSerializer(serializers.Serializer):
source_type = serializers.CharField(help_text="The source type the link is for.")
auth_method = serializers.ChoiceField(
@@ -1856,23 +1860,25 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
.order_by(self.ordering)
)
- @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.
+ instead of passing secrets inline. Only credentials the requesting user stored resolve —
+ ids are listable within a team, so without the owner check any member could consume a
+ teammate's stashed secrets into a source they control. 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()
+ id=credential_id, created_by=cast(User, self.request.user), expires_at__gt=timezone.now()
)
except (PendingSourceCredential.DoesNotExist, ValueError, TypeError, DjangoValidationError):
return (
@@ -1898,6 +1904,9 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
# Stored credentials win over inline keys so an agent can't override what the user entered.
return {**payload, **credential.payload}, credential, None
+ @extend_schema(
+ request=ExternalDataSourceCreateSerializer, responses={201: ExternalDataSourceCreateResponseSerializer}
+ )
def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
@@ -3614,16 +3623,17 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
)
@action(methods=["GET"], detail=False, pagination_class=None)
def stored_credentials(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- """List credentials stored via the source connect page that haven't been consumed yet.
+ """List credentials the requesting user stored via the source connect page that haven't been consumed yet.
Returns metadata only (id, source type, timestamps) — never the secrets themselves. Stored
- credentials are temporary: they disappear once consumed by `setup` or when they expire.
- Newest first, so after a user confirms they've finished the connect page, the first entry
- for the source type is the one to pass to `setup`.
+ credentials are scoped to their creator: only the user who filled the connect page can list
+ or consume them. They are temporary too: they disappear once consumed by `setup` or when
+ they expire. Newest first, so after a user confirms they've finished the connect page, the
+ first entry for the source type is the one to pass to `setup`.
"""
queryset = (
PendingSourceCredential.objects.for_team(self.team_id)
- .filter(expires_at__gt=timezone.now())
+ .filter(created_by=cast(User, request.user), expires_at__gt=timezone.now())
.order_by("-created_at")
)
source_type = request.query_params.get("source_type")
@@ -4367,7 +4377,8 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
"not create the source. Once the user confirms they're done, find the stored credential id via "
f"data-warehouse-stored-credentials-list (source_type='{source_type}', newest first) and call "
'data-warehouse-source-setup with {"credential_id": <id>} in the payload. Stored credentials are '
- "single-use and expire after 24 hours."
+ "single-use, expire after 24 hours, and are only visible to and consumable by the PostHog user "
+ "who entered them — so the page must be filled by the same user this session authenticates as."
),
}
return Response(status=status.HTTP_200_OK, data=SourceConnectLinkSerializer(data).data)
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 5f54691336f5..a6ec5442967a 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
@@ -10782,6 +10782,7 @@ class TestExternalDataSourceSetup(APIBaseTest):
def _store_stripe_credential(self, team=None, **kwargs) -> PendingSourceCredential:
team = team or self.team
+ kwargs.setdefault("created_by", self.user)
return PendingSourceCredential.objects.for_team(team.pk).create(
team=team,
source_type="Stripe",
@@ -10869,6 +10870,25 @@ class TestExternalDataSourceSetup(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "is for 'Stripe'" in response.json()["message"]
+ @parameterized.expand(
+ [
+ ("setup", "setup/"),
+ ("create", ""),
+ ]
+ )
+ def test_consuming_another_team_members_credential_returns_400(self, _name, endpoint):
+ teammate = self._create_user("[email protected]")
+ credential = self._store_stripe_credential(created_by=teammate)
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/{endpoint}",
+ data={"source_type": "Stripe", "payload": {"credential_id": str(credential.pk)}},
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "not found" in response.json()["message"]
+ assert not ExternalDataSource.objects.exists()
+ # The teammate's stash must survive untouched.
+ assert PendingSourceCredential.objects.for_team(self.team.pk).filter(pk=credential.pk).exists()
+
@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(
@@ -11003,8 +11023,9 @@ class TestExternalDataSourceStoreCredentials(APIBaseTest):
assert results[0]["source_type"] == "Stripe"
assert "sk_test_123" not in json.dumps(list_response.json())
- def test_stored_credentials_list_filters_by_source_type_and_hides_expired_and_other_teams(self):
+ def test_stored_credentials_list_filters_by_source_type_and_hides_expired_other_teams_and_other_users(self):
def _create(team, source_type, **kwargs):
+ kwargs.setdefault("created_by", self.user)
return PendingSourceCredential.objects.for_team(team.pk).create(
team=team, source_type=source_type, payload={"key": "secret"}, **kwargs
)
@@ -11014,6 +11035,9 @@ class TestExternalDataSourceStoreCredentials(APIBaseTest):
_create(self.team, "Stripe", expires_at=timezone.now() - timedelta(minutes=1))
other_team = Team.objects.create(organization=self.organization, name="other")
_create(other_team, "Stripe")
+ # A teammate's credential in the same team must not be enumerable — its id would be a
+ # consumable capability.
+ _create(self.team, "Stripe", created_by=self._create_user("[email protected]"))
response = self.client.get(
f"/api/environments/{self.team.pk}/external_data_sources/stored_credentials/?source_type=Stripe"
@@ -11024,10 +11048,10 @@ class TestExternalDataSourceStoreCredentials(APIBaseTest):
def test_stored_credentials_list_orders_newest_first(self):
older = PendingSourceCredential.objects.for_team(self.team.pk).create(
- team=self.team, source_type="Stripe", payload={"key": "secret"}
+ team=self.team, source_type="Stripe", payload={"key": "secret"}, created_by=self.user
)
newer = PendingSourceCredential.objects.for_team(self.team.pk).create(
- team=self.team, source_type="Stripe", payload={"key": "secret"}
+ team=self.team, source_type="Stripe", payload={"key": "secret"}, created_by=self.user
)
PendingSourceCredential.objects.for_team(self.team.pk).filter(pk=older.pk).update(
created_at=timezone.now() - timedelta(hours=1)
diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.ts
index e39f5ab40bd7..933e4af469e4 100644
--- a/products/warehouse_sources/frontend/generated/api.schemas.ts
+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts
@@ -3154,6 +3154,11 @@ export interface ExternalDataSourceCreateApi {
direct_query_enabled?: boolean
}
+export interface ExternalDataSourceCreateResponseApi {
+ /** ID of the created external data source. */
+ id: string
+}
+
export type PatchedExternalDataSourceSerializersApiSchemasItem = { [key: string]: unknown }
/**
diff --git a/products/warehouse_sources/frontend/generated/api.ts b/products/warehouse_sources/frontend/generated/api.ts
index ad9896d4c1da..1828430a4868 100644
--- a/products/warehouse_sources/frontend/generated/api.ts
+++ b/products/warehouse_sources/frontend/generated/api.ts
@@ -17,6 +17,7 @@ import type {
ExternalDataSchemasLogsRetrieveParams,
ExternalDataSourceConnectionOptionApi,
ExternalDataSourceCreateApi,
+ ExternalDataSourceCreateResponseApi,
ExternalDataSourceSerializersApi,
ExternalDataSourcesBulkUpdateSchemasPartialUpdateParams,
ExternalDataSourcesCheckCdcPrerequisitesCreate200,
@@ -308,8 +309,8 @@ export const externalDataSourcesCreate = async (
projectId: string,
externalDataSourceCreateApi: ExternalDataSourceCreateApi,
options?: RequestInit
-): Promise<ExternalDataSourceCreateApi> => {
- return apiMutator<ExternalDataSourceCreateApi>(getExternalDataSourcesCreateUrl(projectId), {
+): Promise<ExternalDataSourceCreateResponseApi> => {
+ return apiMutator<ExternalDataSourceCreateResponseApi>(getExternalDataSourcesCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -1047,12 +1048,13 @@ export const getExternalDataSourcesStoredCredentialsListUrl = (
}
/**
- * List credentials stored via the source connect page that haven't been consumed yet.
+ * List credentials the requesting user stored via the source connect page that haven't been consumed yet.
*
* Returns metadata only (id, source type, timestamps) — never the secrets themselves. Stored
- * credentials are temporary: they disappear once consumed by `setup` or when they expire.
- * Newest first, so after a user confirms they've finished the connect page, the first entry
- * for the source type is the one to pass to `setup`.
+ * credentials are scoped to their creator: only the user who filled the connect page can list
+ * or consume them. They are temporary too: they disappear once consumed by `setup` or when
+ * they expire. Newest first, so after a user confirms they've finished the connect page, the
+ * first entry for the source type is the one to pass to `setup`.
*/
export const externalDataSourcesStoredCredentialsList = async (
projectId: string,
diff --git a/products/warehouse_sources/mcp/tools.yaml b/products/warehouse_sources/mcp/tools.yaml
index c4becf15625d..7e64746d291f 100644
--- a/products/warehouse_sources/mcp/tools.yaml
+++ b/products/warehouse_sources/mcp/tools.yaml
@@ -27,8 +27,9 @@ tools:
credentials: share the returned connect_url with the user, wait for them to confirm they're done, then find
the stored credential via 'data-warehouse-stored-credentials-list' (filter by source_type, newest first) and
call 'data-warehouse-source-setup' with {'credential_id': '<uuid>'} in the payload. Stored credentials are
- single-use and expire after 24 hours. Never ask the user to paste raw database passwords, API keys, or OAuth
- tokens into the chat.
+ single-use, expire after 24 hours, and are only visible to the PostHog user who entered them — the page must
+ be filled by the same user this session authenticates as. Never ask the user to paste raw database
+ passwords, API keys, or OAuth tokens into the chat.
param_overrides:
source_type:
input_schema: ExternalDataSourceTypeSchema
@@ -81,12 +82,13 @@ tools:
list: true
title: List stored source credentials awaiting setup
description: >
- List credentials the user stored via the 'data-warehouse-source-connect-link' page that haven't been
- consumed yet. Returns metadata only (credential_id, source_type, created_at, expires_at) — never the secrets
- themselves. Newest first; filter by source_type. After the user confirms they've finished the connect page,
- take the newest credential_id for the source type and call 'data-warehouse-source-setup' with
- {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use — they are deleted as soon as
- setup consumes them — and expire after 24 hours if never used.
+ List credentials the authenticated user stored via the 'data-warehouse-source-connect-link' page that
+ haven't been consumed yet. Only credentials this user created are visible — a teammate's stored credentials
+ cannot be listed or consumed. Returns metadata only (credential_id, source_type, created_at, expires_at) —
+ never the secrets themselves. Newest first; filter by source_type. After the user confirms they've finished
+ the connect page, take the newest credential_id for the source type and call 'data-warehouse-source-setup'
+ with {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use — they are deleted as
+ soon as setup consumes them — and expire after 24 hours if never used.
external-data-schemas-cancel:
operation: external_data_schemas_cancel_create
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 64dc0b63984b..c28e54140844 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2171,7 +2171,7 @@
}
},
"data-warehouse-source-connect-link": {
- "description": "Return a secure browser link to connect a data warehouse source WITHOUT the user pasting secrets into the chat. The link opens a minimal page rendering the source's full connection form — the user authorizes via OAuth or enters credentials there, whichever the source offers — and the page stores the connection details encrypted and temporarily; it does NOT create the source. This is the preferred, secure way to collect credentials: share the returned connect_url with the user, wait for them to confirm they're done, then find the stored credential via 'data-warehouse-stored-credentials-list' (filter by source_type, newest first) and call 'data-warehouse-source-setup' with {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use and expire after 24 hours. Never ask the user to paste raw database passwords, API keys, or OAuth tokens into the chat.",
+ "description": "Return a secure browser link to connect a data warehouse source WITHOUT the user pasting secrets into the chat. The link opens a minimal page rendering the source's full connection form — the user authorizes via OAuth or enters credentials there, whichever the source offers — and the page stores the connection details encrypted and temporarily; it does NOT create the source. This is the preferred, secure way to collect credentials: share the returned connect_url with the user, wait for them to confirm they're done, then find the stored credential via 'data-warehouse-stored-credentials-list' (filter by source_type, newest first) and call 'data-warehouse-source-setup' with {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use, expire after 24 hours, and are only visible to the PostHog user who entered them — the page must be filled by the same user this session authenticates as. Never ask the user to paste raw database passwords, API keys, or OAuth tokens into the chat.",
"category": "Warehouse sources",
"feature": "warehouse_sources",
"summary": "Get a secure connect link for a source",
@@ -2199,7 +2199,7 @@
}
},
"data-warehouse-stored-credentials-list": {
- "description": "List credentials the user stored via the 'data-warehouse-source-connect-link' page that haven't been consumed yet. Returns metadata only (credential_id, source_type, created_at, expires_at) — never the secrets themselves. Newest first; filter by source_type. After the user confirms they've finished the connect page, take the newest credential_id for the source type and call 'data-warehouse-source-setup' with {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use — they are deleted as soon as setup consumes them — and expire after 24 hours if never used.",
+ "description": "List credentials the authenticated user stored via the 'data-warehouse-source-connect-link' page that haven't been consumed yet. Only credentials this user created are visible — a teammate's stored credentials cannot be listed or consumed. Returns metadata only (credential_id, source_type, created_at, expires_at) — never the secrets themselves. Newest first; filter by source_type. After the user confirms they've finished the connect page, take the newest credential_id for the source type and call 'data-warehouse-source-setup' with {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use — they are deleted as soon as setup consumes them — and expire after 24 hours if never used.",
"category": "Warehouse sources",
"feature": "warehouse_sources",
"summary": "List stored source credentials awaiting setup",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index e53e0a7d5cf7..b1aacf73e3fc 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2200,7 +2200,7 @@
}
},
"data-warehouse-source-connect-link": {
- "description": "Return a secure browser link to connect a data warehouse source WITHOUT the user pasting secrets into the chat. The link opens a minimal page rendering the source's full connection form — the user authorizes via OAuth or enters credentials there, whichever the source offers — and the page stores the connection details encrypted and temporarily; it does NOT create the source. This is the preferred, secure way to collect credentials: share the returned connect_url with the user, wait for them to confirm they're done, then find the stored credential via 'data-warehouse-stored-credentials-list' (filter by source_type, newest first) and call 'data-warehouse-source-setup' with {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use and expire after 24 hours. Never ask the user to paste raw database passwords, API keys, or OAuth tokens into the chat.",
+ "description": "Return a secure browser link to connect a data warehouse source WITHOUT the user pasting secrets into the chat. The link opens a minimal page rendering the source's full connection form — the user authorizes via OAuth or enters credentials there, whichever the source offers — and the page stores the connection details encrypted and temporarily; it does NOT create the source. This is the preferred, secure way to collect credentials: share the returned connect_url with the user, wait for them to confirm they're done, then find the stored credential via 'data-warehouse-stored-credentials-list' (filter by source_type, newest first) and call 'data-warehouse-source-setup' with {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use, expire after 24 hours, and are only visible to the PostHog user who entered them — the page must be filled by the same user this session authenticates as. Never ask the user to paste raw database passwords, API keys, or OAuth tokens into the chat.",
"category": "Warehouse sources",
"feature": "warehouse_sources",
"summary": "Get a secure connect link for a source",
@@ -2228,7 +2228,7 @@
}
},
"data-warehouse-stored-credentials-list": {
- "description": "List credentials the user stored via the 'data-warehouse-source-connect-link' page that haven't been consumed yet. Returns metadata only (credential_id, source_type, created_at, expires_at) — never the secrets themselves. Newest first; filter by source_type. After the user confirms they've finished the connect page, take the newest credential_id for the source type and call 'data-warehouse-source-setup' with {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use — they are deleted as soon as setup consumes them — and expire after 24 hours if never used.",
+ "description": "List credentials the authenticated user stored via the 'data-warehouse-source-connect-link' page that haven't been consumed yet. Only credentials this user created are visible — a teammate's stored credentials cannot be listed or consumed. Returns metadata only (credential_id, source_type, created_at, expires_at) — never the secrets themselves. Newest first; filter by source_type. After the user confirms they've finished the connect page, take the newest credential_id for the source type and call 'data-warehouse-source-setup' with {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use — they are deleted as soon as setup consumes them — and expire after 24 hours if never used.",
"category": "Warehouse sources",
"feature": "warehouse_sources",
"summary": "List stored source credentials awaiting setup",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 78337c82d341..9b334b592384 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -27511,6 +27511,11 @@ export namespace Schemas {
direct_query_enabled?: boolean;
}
+ export interface ExternalDataSourceCreateResponse {
+ /** ID of the created external data source. */
+ id: string;
+ }
+
/**
* One row in `inventory.external_data_sources`.
*/
diff --git a/services/mcp/src/generated/warehouse_sources/api.ts b/services/mcp/src/generated/warehouse_sources/api.ts
index 04a403d7affd..a890e751705d 100644
--- a/services/mcp/src/generated/warehouse_sources/api.ts
+++ b/services/mcp/src/generated/warehouse_sources/api.ts
@@ -2728,12 +2728,13 @@ export const ExternalDataSourcesSetupCreateBody = /* @__PURE__ */ zod.object({
})
/**
- * List credentials stored via the source connect page that haven't been consumed yet.
+ * List credentials the requesting user stored via the source connect page that haven't been consumed yet.
*
* Returns metadata only (id, source type, timestamps) — never the secrets themselves. Stored
- * credentials are temporary: they disappear once consumed by `setup` or when they expire.
- * Newest first, so after a user confirms they've finished the connect page, the first entry
- * for the source type is the one to pass to `setup`.
+ * credentials are scoped to their creator: only the user who filled the connect page can list
+ * or consume them. They are temporary too: they disappear once consumed by `setup` or when
+ * they expire. Newest first, so after a user confirms they've finished the connect page, the
+ * first entry for the source type is the one to pass to `setup`.
*/
export const ExternalDataSourcesStoredCredentialsListParams = /* @__PURE__ */ zod.object({
project_id: zod
diff --git a/services/mcp/src/tools/generated/warehouse_sources.ts b/services/mcp/src/tools/generated/warehouse_sources.ts
index b1cda4932ca8..dd5bf5084e19 100644
--- a/services/mcp/src/tools/generated/warehouse_sources.ts
+++ b/services/mcp/src/tools/generated/warehouse_sources.ts
@@ -475,7 +475,7 @@ const ExternalDataSourcesCreateSchema = ExternalDataSourcesCreateBody.extend({
const externalDataSourcesCreate = (): ToolBase<
typeof ExternalDataSourcesCreateSchema,
- Schemas.ExternalDataSourceCreate
+ Schemas.ExternalDataSourceCreateResponse
> => ({
name: 'external-data-sources-create',
schema: ExternalDataSourcesCreateSchema,
@@ -501,7 +501,7 @@ const externalDataSourcesCreate = (): ToolBase<
body['direct_query_enabled'] = params.direct_query_enabled
}
body['created_via'] = 'mcp'
- const result = await context.api.request<Schemas.ExternalDataSourceCreate>({
+ const result = await context.api.request<Schemas.ExternalDataSourceCreateResponse>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_sources/`,
body,