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(workflows): block deleting integrations used by active workflows (#63015)

Harley Alexander9c06e96956f6
diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.ts
index 9c14170ddd71..a4d430c67942 100644
--- a/frontend/src/lib/integrations/integrationsLogic.ts
+++ b/frontend/src/lib/integrations/integrationsLogic.ts
@@ -361,8 +361,12 @@ export const integrationsLogic = kea<integrationsLogicType>([
children: 'Yes, disconnect',
status: 'danger',
onClick: async () => {
- await api.integrations.delete(id)
- actions.loadIntegrations()
+ try {
+ await api.integrations.delete(id)
+ actions.loadIntegrations()
+ } catch (e) {
+ toastApiError(e)
+ }
},
},
secondaryButton: {
diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.ts
index e5d3c4aa4c1b..46b405471b67 100644
--- a/nodejs/src/cdp/services/messaging/email.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts
@@ -168,14 +168,18 @@ describe('EmailService', () => {
from: { integrationId: 100 },
})
const result = await service.executeSendEmail(invocation)
- expect(result.error).toMatchInlineSnapshot(`"Email integration not found"`)
+ expect(result.error).toMatchInlineSnapshot(
+ `"Email integration not found. The sender configured for this step no longer exists — select a new sender in the workflow's email step."`
+ )
})
it('should validate if the integration is not an email integration', async () => {
invocation.queueParameters = createEmailParams({
from: { integrationId: 3 },
})
const result = await service.executeSendEmail(invocation)
- expect(result.error).toMatchInlineSnapshot(`"Email integration not found"`)
+ expect(result.error).toMatchInlineSnapshot(
+ `"The integration configured for this step is not an email channel — select an email sender in the workflow's email step."`
+ )
})
it('should validate if the integration is not the correct team', async () => {
invocation.teamId = 100
@@ -183,7 +187,9 @@ describe('EmailService', () => {
from: { integrationId: 1 },
})
const result = await service.executeSendEmail(invocation)
- expect(result.error).toMatchInlineSnapshot(`"Email integration not found"`)
+ expect(result.error).toMatchInlineSnapshot(
+ `"Email integration not found. The sender configured for this step no longer exists — select a new sender in the workflow's email step."`
+ )
})
it('should validate if the email domain is not verified', async () => {
invocation.queueParameters = createEmailParams({
diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.ts
index 1b7e279eb77c..b0d836b0af39 100644
--- a/nodejs/src/cdp/services/messaging/email.service.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.ts
@@ -86,8 +86,16 @@ export class EmailService {
let success: boolean = false
try {
- if (!integration || integration.kind !== 'email' || integration.team_id !== invocation.teamId) {
- throw new Error('Email integration not found')
+ // Wrong-team references deliberately read as not-found so an ID's existence on another team can't be probed
+ if (!integration || integration.team_id !== invocation.teamId) {
+ throw new Error(
+ "Email integration not found. The sender configured for this step no longer exists — select a new sender in the workflow's email step."
+ )
+ }
+ if (integration.kind !== 'email') {
+ throw new Error(
+ "The integration configured for this step is not an email channel — select an email sender in the workflow's email step."
+ )
}
const from = this.resolveFromSender(integration)
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index 2efaa9fe579a..ad873b0245e4 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -75,6 +75,8 @@ from posthog.permissions import (
from posthog.rate_limit import GitHubRepositoryRefreshThrottle
from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
+from products.workflows.backend.services.integration_usage import get_active_hog_flows_using_integration
+
logger = structlog.get_logger(__name__)
GITHUB_REPOSITORY_NAME_RE = re.compile(r"[A-Za-z0-9_.\-]+")
@@ -628,6 +630,16 @@ class IntegrationViewSet(
return super().get_throttles()
def perform_destroy(self, instance) -> None:
+ flows_using_integration = get_active_hog_flows_using_integration(
+ team_id=instance.team_id, integration_id=instance.id
+ )
+ if flows_using_integration:
+ flow_names = ", ".join(sorted(flow.name or str(flow.id) for flow in flows_using_integration))
+ raise ValidationError(
+ f"This integration is used by active workflows: {flow_names}. "
+ "Update those workflows to use a different integration before disconnecting it."
+ )
+
if instance.kind == "stripe":
try:
stripe_integration = StripeIntegration(instance)
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 476a9e9052cb..1923a339dce2 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -39,6 +39,9 @@ from posthog.models.user_integration import UserIntegration
from posthog.models.utils import hash_key_value
from posthog.rate_limit import GitHubRepositoryRefreshThrottle
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.workflows.backend.models import HogFlow
+
class TestSlackIntegration:
@pytest.fixture(autouse=True)
@@ -3396,3 +3399,163 @@ class TestGitHubIntegrationUninstall:
assert response.status_code == status.HTTP_204_NO_CONTENT
assert not Integration.objects.filter(id=integration.id).exists()
+
+
+class TestIntegrationDeletionWorkflowGuard:
+ @pytest.fixture(autouse=True)
+ def setup_integration(self, db):
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.user = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
+ )
+ self.integration = Integration.objects.create(
+ team=self.team,
+ kind="email",
+ config={"email": "[email protected]", "name": "Test", "domain": "posthog.com", "verified": True},
+ created_by=self.user,
+ )
+
+ def _email_actions(self, integration_id: int) -> list[dict]:
+ return [
+ {"id": "trigger_node", "name": "Trigger", "type": "trigger", "config": {"type": "event", "filters": {}}},
+ {
+ "id": "action_email_1",
+ "name": "Welcome Email",
+ "type": "function_email",
+ "config": {
+ "inputs": {
+ "email": {
+ "value": {
+ "to": {"email": "{{ person.properties.email }}", "name": ""},
+ "from": {"integrationId": integration_id},
+ "subject": "Welcome!",
+ "html": "",
+ "text": "",
+ }
+ }
+ }
+ },
+ },
+ ]
+
+ def _create_flow(self, status: str = "active", actions: list | None = None) -> HogFlow:
+ return HogFlow.objects.create(
+ team=self.team,
+ name="Welcome Email Sequence",
+ status=status,
+ actions=actions if actions is not None else self._email_actions(self.integration.id),
+ edges=[],
+ )
+
+ def _delete(self, client: HttpClient):
+ client.force_login(self.user)
+ return client.delete(f"/api/environments/{self.team.pk}/integrations/{self.integration.id}/")
+
+ def test_destroy_blocked_when_active_workflow_references_integration(self, client: HttpClient):
+ self._create_flow()
+
+ response = self._delete(client)
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "Welcome Email Sequence" in response.content.decode()
+ assert Integration.objects.filter(id=self.integration.id).exists()
+
+ @pytest.mark.parametrize("flow_status", ["draft", "archived"])
+ def test_destroy_allowed_when_workflow_not_active(self, flow_status: str, client: HttpClient):
+ self._create_flow(status=flow_status)
+
+ with patch("posthog.api.integration.EmailIntegration"):
+ response = self._delete(client)
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not Integration.objects.filter(id=self.integration.id).exists()
+
+ def test_destroy_allowed_when_workflow_references_other_integration(self, client: HttpClient):
+ self._create_flow(actions=self._email_actions(self.integration.id + 1))
+
+ with patch("posthog.api.integration.EmailIntegration"):
+ response = self._delete(client)
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not Integration.objects.filter(id=self.integration.id).exists()
+
+ @pytest.mark.parametrize(
+ "reference_kind,template_id",
+ [
+ # Bare-ID inputs are only identifiable as integrations via the template's inputs_schema
+ ("bare_id_via_schema", "template-test-slack"),
+ # Dict-form inputs are caught by the recursive config walk, no template needed
+ ("dict_value", "template-unknown"),
+ ],
+ )
+ def test_destroy_blocked_when_function_action_references_integration(
+ self, reference_kind: str, template_id: str, client: HttpClient
+ ):
+ input_value: int | dict
+ if reference_kind == "bare_id_via_schema":
+ HogFunctionTemplate.objects.create(
+ template_id=template_id,
+ sha="abc123",
+ name="Slack",
+ code="return event",
+ inputs_schema=[{"key": "slack_workspace", "type": "integration", "label": "Slack workspace"}],
+ type="destination",
+ )
+ input_value = self.integration.id
+ else:
+ input_value = {"integrationId": self.integration.id}
+ self._create_flow(
+ actions=[
+ {
+ "id": "action_function_1",
+ "name": "Notify Slack",
+ "type": "function",
+ "config": {
+ "template_id": template_id,
+ "inputs": {"slack_workspace": {"value": input_value}},
+ },
+ },
+ ]
+ )
+
+ response = self._delete(client)
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert Integration.objects.filter(id=self.integration.id).exists()
+
+ def test_destroy_survives_deeply_nested_action_config(self, client: HttpClient):
+ nested: dict = {"integrationId": self.integration.id}
+ for _ in range(1500):
+ nested = {"_x": nested}
+ self._create_flow(
+ actions=[{"id": "action_function_1", "name": "Evil", "type": "function", "config": {"inputs": nested}}]
+ )
+
+ with patch("posthog.api.integration.EmailIntegration"):
+ response = self._delete(client)
+
+ # The reference sits beyond the traversal depth cap: deletion proceeds rather than 500ing
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not Integration.objects.filter(id=self.integration.id).exists()
+
+ @pytest.mark.parametrize(
+ "action_type,config",
+ [
+ # Non-function actions don't consume integrations
+ ("delay", {"duration": "5m"}),
+ # Function actions only consume integrations via config.inputs
+ ("function", {"template_id": "template-unknown", "inputs": {}}),
+ ],
+ )
+ def test_destroy_allowed_when_integration_id_in_non_consuming_config(
+ self, action_type: str, config: dict, client: HttpClient
+ ):
+ config = {**config, "integrationId": self.integration.id}
+ self._create_flow(actions=[{"id": "action_1", "name": "Planted", "type": action_type, "config": config}])
+
+ with patch("posthog.api.integration.EmailIntegration"):
+ response = self._delete(client)
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not Integration.objects.filter(id=self.integration.id).exists()
diff --git a/products/workflows/backend/services/integration_usage.py b/products/workflows/backend/services/integration_usage.py
new file mode 100644
index 000000000000..72cf05e5c1ae
--- /dev/null
+++ b/products/workflows/backend/services/integration_usage.py
@@ -0,0 +1,69 @@
+from typing import Any
+
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.workflows.backend.models import HogFlow
+
+# Action configs are user-controlled JSON; cap traversal depth so a crafted deeply-nested
+# config can't RecursionError the deletion guard (legitimate configs nest ~5 levels).
+_MAX_CONFIG_DEPTH = 20
+
+_TemplateCache = dict[str, HogFunctionTemplate | None]
+
+
+def _node_references_integration(node: Any, integration_id: int, depth: int = 0) -> bool:
+ if depth > _MAX_CONFIG_DEPTH:
+ return False
+ if isinstance(node, dict):
+ value = node.get("integrationId")
+ if value is not None and str(value) == str(integration_id):
+ return True
+ return any(_node_references_integration(child, integration_id, depth + 1) for child in node.values())
+ if isinstance(node, list):
+ return any(_node_references_integration(item, integration_id, depth + 1) for item in node)
+ return False
+
+
+def _function_action_references_integration(action: dict, integration_id: int, template_cache: _TemplateCache) -> bool:
+ # Function actions store integration inputs as bare IDs; only the template's
+ # inputs_schema knows which inputs are integration-typed.
+ config = action.get("config") or {}
+ template_id = config.get("template_id")
+ if not template_id:
+ return False
+ if template_id not in template_cache:
+ template_cache[template_id] = HogFunctionTemplate.get_template(template_id)
+ template = template_cache[template_id]
+ if not template:
+ return False
+ inputs = config.get("inputs") or {}
+ for schema_item in template.inputs_schema or []:
+ if schema_item.get("type") != "integration":
+ continue
+ value = (inputs.get(schema_item.get("key")) or {}).get("value")
+ if isinstance(value, dict):
+ value = value.get("integrationId")
+ if value is not None and str(value) == str(integration_id):
+ return True
+ return False
+
+
+def _action_references_integration(action: dict, integration_id: int, template_cache: _TemplateCache) -> bool:
+ # Integrations are only consumed by function-style actions, via config.inputs — scanning
+ # wider would let a planted integrationId in an unused field block deletion.
+ if "function" not in (action.get("type") or ""):
+ return False
+ if _node_references_integration((action.get("config") or {}).get("inputs"), integration_id):
+ return True
+ return _function_action_references_integration(action, integration_id, template_cache)
+
+
+def get_active_hog_flows_using_integration(team_id: int, integration_id: int) -> list[HogFlow]:
+ """Active workflows whose live config references the given integration."""
+ template_cache: _TemplateCache = {}
+ return [
+ flow
+ for flow in HogFlow.objects.filter(team_id=team_id, status=HogFlow.State.ACTIVE)
+ if any(
+ _action_references_integration(action, integration_id, template_cache) for action in (flow.actions or [])
+ )
+ ]