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): edit webhook source inputs after creation (#57200)

Marcus Hof5069f547113a
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 75af49ad46d9..eabbccd140a4 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5763,6 +5763,8 @@ export interface WebhookExternalStatus {
error?: string
}
+export type WebhookInputValue = { secret: true } | { value: unknown }
+
export interface WebhookInfo {
supports_webhooks: boolean
exists: boolean
@@ -5775,6 +5777,7 @@ export interface WebhookInfo {
}
webhook_url?: string
schema_mapping?: Record<string, string>
+ inputs?: Record<string, WebhookInputValue>
external_status?: WebhookExternalStatus | null
}
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.py
index 25b5ee59ca8c..2cbcc1830a81 100644
--- a/products/data_warehouse/backend/api/external_data_source.py
+++ b/products/data_warehouse/backend/api/external_data_source.py
@@ -31,6 +31,7 @@ from posthog.schema import (
from posthog.hogql.database.database import Database
+from posthog.api.hog_function import HogFunctionSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.exceptions_capture import capture_exception
@@ -1828,6 +1829,10 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
if hog_function.inputs:
schema_mapping = hog_function.inputs.get("schema_mapping", {}).get("value", {})
+ webhook_field_names = {f.name for f in (source.get_source_config.webhookFields or [])}
+ all_inputs = HogFunctionSerializer(hog_function).data.get("inputs") or {}
+ webhook_inputs = {k: v for k, v in all_inputs.items() if k in webhook_field_names}
+
return Response(
status=status.HTTP_200_OK,
data={
@@ -1842,6 +1847,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
},
"webhook_url": webhook_url,
"schema_mapping": schema_mapping,
+ "inputs": webhook_inputs,
"external_status": dataclasses.asdict(external_status) if external_status else None,
},
)
@@ -1953,12 +1959,12 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
data={"message": f"Invalid input keys: {', '.join(invalid_keys)}"},
)
- required_fields = [f.name for f in webhook_fields if hasattr(f, "required") and f.required]
- missing_fields = [name for name in required_fields if not inputs.get(name)]
- if missing_fields:
+ required_fields = [f.name for f in webhook_fields if getattr(f, "required", False)]
+ blanked_required = [name for name in required_fields if name in inputs and not inputs[name]]
+ if blanked_required:
return Response(
status=status.HTTP_400_BAD_REQUEST,
- data={"message": f"Missing required fields: {', '.join(missing_fields)}"},
+ data={"message": f"Missing required fields: {', '.join(blanked_required)}"},
)
schema_ids = list(
diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.py
index af99871c433f..ad4423728d19 100644
--- a/products/data_warehouse/backend/api/test/test_external_data_source.py
+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py
@@ -4,7 +4,7 @@ from typing import cast
from freezegun import freeze_time
from posthog.test.base import APIBaseTest, FuzzyInt
-from unittest.mock import Mock, patch
+from unittest.mock import Mock, PropertyMock, patch
from django.conf import settings
from django.test import override_settings
@@ -4767,6 +4767,134 @@ class TestCreateWebhook(APIBaseTest):
assert "No webhook function found" in response.json()["message"]
mock_inputs_updated.assert_not_called()
+ @patch("posthog.temporal.data_imports.sources.stripe.source.is_webhook_feature_flag_enabled", return_value=True)
+ @patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.create_webhook")
+ def test_update_webhook_inputs_rejects_blanked_required_field(self, mock_create_webhook, _mock_flag):
+ mock_create_webhook.return_value = self._webhook_result()
+ self._create_hog_function_template()
+ source = self._create_stripe_source()
+ self._create_webhook_schema(source, STRIPE_CUSTOMER_RESOURCE_NAME)
+ self.client.post(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/create_webhook/")
+
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/update_webhook_inputs/",
+ data={"inputs": {"signing_secret": ""}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "signing_secret" in response.json()["message"]
+
+ @patch("posthog.temporal.data_imports.sources.stripe.source.is_webhook_feature_flag_enabled", return_value=True)
+ @patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.create_webhook")
+ def test_update_webhook_inputs_partial_update_preserves_other_required_fields(
+ self, mock_create_webhook, _mock_flag
+ ):
+ from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
+
+ from posthog.models.hog_functions.hog_function import HogFunction
+
+ mock_create_webhook.return_value = self._webhook_result(extra_inputs={"signing_secret": "whsec_initial"})
+ self._create_hog_function_template()
+ source = self._create_stripe_source()
+ self._create_webhook_schema(source, STRIPE_CUSTOMER_RESOURCE_NAME)
+ self.client.post(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/create_webhook/")
+
+ # Inject a second required webhook field into the source config so we can test
+ # that a partial update which omits one required field is accepted while still
+ # preserving the existing value on the HogFunction.
+ from posthog.temporal.data_imports.sources import SourceRegistry
+
+ from products.data_warehouse.backend.types import ExternalDataSourceType
+
+ original_source = SourceRegistry.get_source(ExternalDataSourceType("Stripe"))
+ original_config = original_source.get_source_config
+ extra_field = SourceFieldInputConfig(
+ name="extra_required",
+ label="Extra required",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ )
+ patched_config = original_config.model_copy(
+ update={"webhookFields": [*(original_config.webhookFields or []), extra_field]}
+ )
+
+ with patch(
+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.get_source_config",
+ new_callable=PropertyMock,
+ return_value=patched_config,
+ ):
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/update_webhook_inputs/",
+ data={"inputs": {"signing_secret": "whsec_rotated"}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["success"] is True
+
+ hog_function = HogFunction.objects.get(team=self.team, type="warehouse_source_webhook")
+ assert hog_function.encrypted_inputs is not None
+ assert hog_function.encrypted_inputs["signing_secret"]["value"] == "whsec_rotated"
+
+ def test_update_webhook_inputs_rejects_non_webhook_source(self):
+ source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ destination_id=str(uuid.uuid4()),
+ source_type="Postgres",
+ created_by=self.user,
+ job_inputs={"host": "localhost"},
+ )
+
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/update_webhook_inputs/",
+ data={"inputs": {"signing_secret": "whsec_test"}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "does not support webhooks" in response.json()["message"]
+
+ @patch("posthog.temporal.data_imports.sources.stripe.source.is_webhook_feature_flag_enabled", return_value=True)
+ def test_update_webhook_inputs_rejects_empty_payload(self, _mock_flag):
+ source = self._create_stripe_source()
+
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/update_webhook_inputs/",
+ data={"inputs": {}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "No inputs provided" in response.json()["message"]
+
+ @patch("posthog.temporal.data_imports.sources.stripe.source.is_webhook_feature_flag_enabled", return_value=True)
+ @patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.create_webhook")
+ def test_update_webhook_inputs_requires_eligible_schema(self, mock_create_webhook, _mock_flag):
+ # Webhook is created (HogFunction exists), but the schema's should_sync is then
+ # turned off — so no eligible schemas remain. The action must reject the update.
+ mock_create_webhook.return_value = self._webhook_result()
+ self._create_hog_function_template()
+ source = self._create_stripe_source()
+ schema = self._create_webhook_schema(source, STRIPE_CUSTOMER_RESOURCE_NAME)
+ self.client.post(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/create_webhook/")
+
+ schema.should_sync = False
+ schema.save(update_fields=["should_sync"])
+
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/update_webhook_inputs/",
+ data={"inputs": {"signing_secret": "whsec_rotated"}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "No eligible schemas found" in response.json()["message"]
+
@patch("posthog.temporal.data_imports.sources.stripe.source.is_webhook_feature_flag_enabled", return_value=True)
@patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.create_webhook")
def test_create_webhook_maps_all_webhook_schemas(self, mock_create_webhook, _mock_flag):
@@ -5261,6 +5389,47 @@ class TestWebhookInfo(APIBaseTest):
assert data["exists"] is True
assert data["external_status"] is None
+ @patch("posthog.temporal.data_imports.sources.stripe.source.is_webhook_feature_flag_enabled", return_value=True)
+ @patch(
+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.get_external_webhook_info", return_value=None
+ )
+ def test_webhook_info_masks_set_secret_input(self, _mock_info, _mock_flag):
+ from posthog.models.hog_functions.hog_function import HogFunction
+
+ source = self._create_stripe_source()
+ hog_function = self._create_hog_function(source)
+ hog_function.inputs_schema = [
+ *hog_function.inputs_schema,
+ {"type": "string", "key": "signing_secret", "label": "Signing secret", "required": True, "secret": True},
+ ]
+ hog_function.encrypted_inputs = {"signing_secret": {"value": "whsec_existing"}}
+ hog_function.save()
+ # Sanity check the model routed the secret correctly.
+ hog_function.refresh_from_db()
+ assert (
+ HogFunction.objects.get(pk=hog_function.pk).encrypted_inputs["signing_secret"]["value"] == "whsec_existing"
+ )
+
+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/webhook_info/")
+
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data["inputs"] == {"signing_secret": {"secret": True}}
+
+ @patch("posthog.temporal.data_imports.sources.stripe.source.is_webhook_feature_flag_enabled", return_value=True)
+ @patch(
+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.get_external_webhook_info", return_value=None
+ )
+ def test_webhook_info_omits_unset_inputs(self, _mock_info, _mock_flag):
+ source = self._create_stripe_source()
+ self._create_hog_function(source)
+
+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/webhook_info/")
+
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data["inputs"] == {}
+
class TestDeleteWebhook(APIBaseTest):
def _create_stripe_source(self, job_inputs=None) -> ExternalDataSource:
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/WebhookTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/WebhookTab.tsx
index f0ba17d32fb9..3cb2afeda8aa 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/WebhookTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/WebhookTab.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
import { LemonBanner, LemonButton, LemonSkeleton, LemonTable, LemonTag } from '@posthog/lemon-ui'
@@ -9,8 +10,10 @@ import { AppMetricSummary } from 'lib/components/AppMetrics/AppMetricSummary'
import { LemonCard } from 'lib/lemon-ui/LemonCard'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { SourceConfig, SourceFieldConfig } from '~/queries/schema/schema-general'
import { WebhookInfo } from '~/types'
+import { sourceFieldToElement } from '../../../shared/components/forms/SourceForm'
import {
WebhookRefreshButton,
WebhookSetupForm,
@@ -103,6 +106,9 @@ export function WebhookTab({ id, tabId }: { id: string; tabId?: string }): JSX.E
/>
)}
<WebhookDetailsSection webhookInfo={webhookInfo} />
+ {sourceConfig && (sourceConfig.webhookFields?.length ?? 0) > 0 && (
+ <WebhookConfigurationSection sourceConfig={sourceConfig} formLogicProps={logicProps} />
+ )}
{webhookInfo.hog_function?.id && <WebhookMetricsSection hogFunctionId={webhookInfo.hog_function.id} />}
{mappedTables.length > 0 && <MappedTablesSection mappedTables={mappedTables} />}
<WebhookDeleteSection canDelete={canDeleteWebhook} deleting={webhookDeleting} onDelete={deleteWebhook} />
@@ -110,6 +116,33 @@ export function WebhookTab({ id, tabId }: { id: string; tabId?: string }): JSX.E
)
}
+function WebhookConfigurationSection({
+ sourceConfig,
+ formLogicProps,
+}: {
+ sourceConfig: SourceConfig
+ formLogicProps: { id: string; tabId?: string }
+}): JSX.Element {
+ const { webhookFieldInputs, isWebhookFieldInputsSubmitting } = useValues(webhookTabLogic(formLogicProps))
+ const webhookFields = sourceConfig.webhookFields ?? []
+
+ return (
+ <LemonCard hoverEffect={false} className="space-y-3">
+ <h3 className="text-lg font-semibold">Configuration</h3>
+ <Form logic={webhookTabLogic} props={formLogicProps} formKey="webhookFieldInputs" enableFormOnSubmit>
+ <div className="space-y-3 ph-no-capture">
+ {webhookFields.map((field: SourceFieldConfig) =>
+ sourceFieldToElement(field, sourceConfig, webhookFieldInputs[field.name], true)
+ )}
+ <LemonButton type="primary" htmlType="submit" loading={isWebhookFieldInputsSubmitting}>
+ Save changes
+ </LemonButton>
+ </div>
+ </Form>
+ </LemonCard>
+ )
+}
+
function WebhookMetricsSection({ hogFunctionId }: { hogFunctionId: string }): JSX.Element {
const logicKey = `webhook-metrics-${hogFunctionId}`
const logic = appMetricsLogic({
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/webhookTabLogic.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/webhookTabLogic.ts
index d7527fcb9148..bc2720cb3ede 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/webhookTabLogic.ts
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/webhookTabLogic.ts
@@ -169,10 +169,18 @@ export const webhookTabLogic = kea<webhookTabLogicType>([
defaults: {} as Record<string, any>,
errors: (sourceValues) => {
const webhookFields = values.sourceConfig?.webhookFields ?? []
- return getErrorsForFields(webhookFields, {
- prefix: '',
- payload: sourceValues as Record<string, any>,
- }).payload
+ return getErrorsForFields(
+ webhookFields,
+ {
+ prefix: '',
+ payload: sourceValues as Record<string, any>,
+ },
+ // In edit mode, secret fields whose current value is the masked
+ // `{secret: true}` marker are already set on the server. Treat
+ // them as satisfying the required check so users can update other
+ // fields without re-entering the secret.
+ { allowBlankSensitiveFields: true }
+ ).payload
},
submit: async () => {
actions.submitWebhookFields()
@@ -180,6 +188,24 @@ export const webhookTabLogic = kea<webhookTabLogicType>([
},
})),
listeners(({ actions, props, values }) => ({
+ loadWebhookInfoSuccess: ({ webhookInfo }) => {
+ // Server returns each input either as `{secret: true}` (masked) or `{value: ...}`
+ // (HogFunctionSerializer convention). Unwrap non-secret values and use them as
+ // the form's new defaults via reset — that way any stale plaintext typed in a
+ // prior edit gets cleared, and `webhookFieldInputsChanged` only flips when the
+ // user actually edits a field. Mirrors the HogFunctions configuration logic
+ // pattern (`loadHogFunctionSuccess: () => actions.resetForm()`).
+ const inputs = webhookInfo?.inputs
+ const nonSecretValues: Record<string, any> = {}
+ if (inputs) {
+ for (const [name, entry] of Object.entries(inputs)) {
+ if (entry && typeof entry === 'object' && !Array.isArray(entry) && 'value' in entry) {
+ nonSecretValues[name] = (entry as { value: unknown }).value
+ }
+ }
+ }
+ actions.resetWebhookFieldInputs(nonSecretValues)
+ },
createWebhook: async () => {
try {
const result = await api.externalDataSources.createWebhook(props.id)
@@ -202,15 +228,31 @@ export const webhookTabLogic = kea<webhookTabLogicType>([
actions.loadWebhookInfo()
},
submitWebhookFields: async () => {
- const fieldValues = values.webhookFieldInputs
- if (Object.keys(fieldValues).length > 0) {
- try {
- await api.externalDataSources.updateWebhookInputs(props.id, fieldValues)
- lemonToast.success('Webhook inputs saved')
- actions.loadWebhookInfo()
- } catch (e: any) {
- lemonToast.error(e.data?.message ?? e.message ?? 'Failed to update webhook inputs')
- }
+ // Only send fields that have a truthy value. Empty strings for fields the
+ // user never touched (e.g. a masked secret left alone) must not overwrite
+ // the existing server value.
+ const payload = Object.fromEntries(
+ Object.entries(values.webhookFieldInputs).filter(([, value]) => {
+ if (value === undefined || value === null || value === '') {
+ return false
+ }
+ return true
+ })
+ )
+ if (Object.keys(payload).length === 0) {
+ lemonToast.info('No changes to save')
+ return
+ }
+ try {
+ await api.externalDataSources.updateWebhookInputs(props.id, payload)
+ lemonToast.success('Webhook inputs saved')
+ // Clear typed plaintext immediately so the form doesn't keep the rotated
+ // secret in client state. `loadWebhookInfoSuccess` will then re-seed
+ // defaults from the masked server response.
+ actions.resetWebhookFieldInputs()
+ actions.loadWebhookInfo()
+ } catch (e: any) {
+ lemonToast.error(e.data?.message ?? e.message ?? 'Failed to update webhook inputs')
}
},
deleteWebhook: async () => {