: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(workflows): enforce the staff email suspension at send time (#83055)
Daniel Marchuka1062d96c9b3
diff --git a/nodejs/src/cdp/services/managers/team-workflows-config.service.ts b/nodejs/src/cdp/services/managers/team-workflows-config.service.tsindex 687d951a113d..06e4fafeaa48 100644--- a/nodejs/src/cdp/services/managers/team-workflows-config.service.ts+++ b/nodejs/src/cdp/services/managers/team-workflows-config.service.ts@@ -1,5 +1,6 @@import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'import { LazyLoader } from '~/common/utils/lazy-loader'+import { logger } from '~/common/utils/logger'// Mirrors EmailTrackingConsentMode in products/workflows/backend/models/team_workflows_config.pyexport type EmailTrackingConsentMode = 'off' | 'opt_out' | 'opt_in'@@ -7,11 +8,13 @@ export type EmailTrackingConsentMode = 'off' | 'opt_out' | 'opt_in'export type TeamWorkflowsConfig = {capture_workflows_engagement_events: booleanemail_tracking_consent_mode: EmailTrackingConsentMode+ email_sending_suspended: boolean}const DEFAULT_CONFIG: TeamWorkflowsConfig = {capture_workflows_engagement_events: false,email_tracking_consent_mode: 'off',+ email_sending_suspended: false,}/**@@ -45,14 +48,30 @@ export class TeamWorkflowsConfigService {return config.email_tracking_consent_mode}+ /**+ * Team-level kill switch, set by staff when a team's sender reputation puts shared SES+ * deliverability at risk. Fails open: a lookup error must never block legitimate sends.+ */+ public async isEmailSendingSuspended(teamId: number): Promise<boolean> {+ try {+ const config = await this.get(teamId)+ return config.email_sending_suspended+ } catch (error) {+ logger.error('[TeamWorkflowsConfig] Failed to check email sending suspension', { teamId, error })+ return false+ }+ }+private async fetchConfigs(teamIds: string[]): Promise<Record<string, TeamWorkflowsConfig>> {const result = await this.postgres.query<{team_id: numbercapture_workflows_engagement_events: booleanemail_tracking_consent_mode: EmailTrackingConsentMode+ email_sending_suspended: boolean}>(PostgresUse.COMMON_READ,- `SELECT team_id, capture_workflows_engagement_events, email_tracking_consent_mode+ `SELECT team_id, capture_workflows_engagement_events, email_tracking_consent_mode,+ email_sending_suspended_at IS NOT NULL AS email_sending_suspendedFROM workflows_teamworkflowsconfigWHERE team_id = ANY($1)`,[teamIds.map(Number)],@@ -67,6 +86,7 @@ export class TeamWorkflowsConfigService {configs[String(row.team_id)] = {capture_workflows_engagement_events: row.capture_workflows_engagement_events,email_tracking_consent_mode: row.email_tracking_consent_mode ?? 'off',+ email_sending_suspended: row.email_sending_suspended,}}return configsdiff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.tsindex a1ea7cda8c24..2eb6c1f79be3 100644--- a/nodejs/src/cdp/services/messaging/email.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts@@ -6,6 +6,7 @@ import { createExampleInvocation, insertIntegration } from '~/cdp/_tests/fixtureimport { CyclotronInvocationQueueParametersEmailType } from '~/cdp/schema/cyclotron'import { CyclotronJobInvocationHogFunction } from '~/cdp/types'import { closeHub, createHub } from '~/common/utils/db/hub'+import { PostgresUse } from '~/common/utils/db/postgres'import { waitForExpect } from '~/tests/helpers/expectations'import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'@@ -540,6 +541,58 @@ describe('EmailService', () => {})})+ describe('team suspension enforcement at send time', () => {+ // Guards the reputation kill switch: while a team is suspended, no send path may+ // reach SES — including editor test sends, which count against the tenant too.+ // The first two write a real row so they also cover the service's SELECT; mocking+ // isEmailSendingSuspended would pass with the column missing from the query.+ const suspendTeam = async (): Promise<void> => {+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO workflows_teamworkflowsconfig+ (team_id, capture_workflows_engagement_events, email_tracking_consent_mode,+ email_sending_suspended_at, email_sending_suspension_reason)+ VALUES ($1, false, 'off', now(), 'testing suspension')+ ON CONFLICT (team_id) DO UPDATE SET email_sending_suspended_at = now()`,+ [team.id],+ 'test-suspend-email-sending'+ )+ }++ it('does not call SES while the team is suspended and records email_suspended', async () => {+ await suspendTeam()+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })++ const result = await service.executeSendEmail(invocation)++ expect(sendEmailSpy).not.toHaveBeenCalled()+ expect(result.metrics.map((m) => m.metric_name)).toEqual(['email_suspended'])+ expect(invocation.state.vmState?.stack).toEqual([{ success: false }])+ })++ it('blocks editor test sends while suspended without recording metrics', async () => {+ await suspendTeam()+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })++ const result = await service.executeSendEmail(invocation, true)++ expect(sendEmailSpy).not.toHaveBeenCalled()+ expect(result.metrics).toEqual([])+ })++ it('fails open when the suspension lookup errors', async () => {+ // The config lookup rejecting must never block a legitimate send. Rejects once:+ // the suspension check is the first config read; later reads use the real loader.+ jest.spyOn(service['teamWorkflowsConfigService'], 'get').mockRejectedValueOnce(new Error('pg down'))+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })++ const result = await service.executeSendEmail(invocation)++ expect(sendEmailSpy).toHaveBeenCalledTimes(1)+ expect(result.metrics.map((m) => m.metric_name)).toContain('email_sent')+ })+ })+it('should include cc addresses in SES destination', async () => {sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })invocation.queueParameters = createEmailParams({diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.tsindex 8c1ceebe07b7..ba179c0f688f 100644--- a/nodejs/src/cdp/services/messaging/email.service.ts+++ b/nodejs/src/cdp/services/messaging/email.service.ts@@ -185,6 +185,26 @@ export class EmailService {let trackingEnabled = truetry {+ // Team-level kill switch: staff suspend all workflow email for a team whose sender+ // reputation endangers shared SES deliverability. Same choke-point placement as the+ // suppression check below so no upstream route can bypass it. Test sends are blocked+ // too — they hit SES and count against the tenant all the same.+ if (await this.teamWorkflowsConfigService.isEmailSendingSuspended(invocation.teamId)) {+ addLog('warn', 'Skipping send: email sending is suspended for this project')+ if (!isTest) {+ result.metrics.push({+ team_id: invocation.teamId,+ app_source_id: invocation.parentRunId ?? invocation.functionId,+ instance_id: invocation.state.actionId || invocation.id,+ metric_kind: 'email',+ metric_name: 'email_suspended',+ count: 1,+ })+ }+ result.invocation.state.vmState?.stack.push({ success: false })+ return result+ }+// Wrong-team references deliberately read as not-found so an ID's existence on another team can't be probedif (!integration || integration.team_id !== invocation.teamId) {throw new Error(diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex b9ec9f261651..0ecc91dc3eb2 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -243,6 +243,7 @@ export type MinimalAppMetric = {| 'email_bounced_undetermined'| 'email_bounce_prevented'| 'email_suppressed'+ | 'email_suspended'| 'email_blocked'| 'email_spam'| 'email_unsubscribed'diff --git a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.tsindex 908d6941712a..03c2aad62189 100644--- a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts+++ b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts@@ -118,6 +118,7 @@ export type EmailMetric =| 'email_blocked'| 'email_spam'| 'email_untracked'+ | 'email_suspended'export type PushMetric = 'push_sent' | 'push_skipped' | 'push_failed' | 'push_opened'@@ -182,6 +183,7 @@ export const METRIC_COLORS: Record<string, string> = {Blocked: getColorVar('data-color-8'),'Marked as spam': getColorVar('data-color-9'),Untracked: getColorVar('data-color-10'),+ Suspended: getColorVar('data-color-11'),Skipped: getColorVar('data-color-2'),// Workflow run + batch-job metricsSuccess: getColorVar('success'),@@ -303,6 +305,13 @@ export const WORKFLOW_EMAIL_METRICS: Record<color: METRIC_COLORS['Untracked'],metricNames: ['email_untracked'],},+ email_suspended: {+ name: 'Suspended',+ description:+ 'Total number of emails that were not sent because email sending is suspended for this project. Contact support to get sending re-enabled.',+ color: METRIC_COLORS['Suspended'],+ metricNames: ['email_suspended'],+ },}// Push has no delivery-receipt channel like email's SES webhook (FCM/APNs respond synchronously), so@@ -355,6 +364,8 @@ export const EMAIL_METRIC_INVOCATION_FILTERS: Partial<// MX-validation skips log "Skipping send: …" at INFO (see HogFunctionHandler in the plugin server).email_bounce_prevented: { search: 'Skipping send', levels: ['INFO'] },email_blocked: { search: 'Complaint', levels: ['WARN', 'ERROR'] },+ // Suspension skips log "Skipping send: email sending is suspended …" at WARN (EmailService).+ email_suspended: { search: 'Skipping send', levels: ['WARN'] },}// Build the router search params that point the Invocations tab at the runs behind the given email@@ -393,6 +404,7 @@ const EMAIL_METRICS: EmailMetric[] = ['email_blocked','email_spam','email_untracked',+ 'email_suspended',]const PUSH_METRICS: PushMetric[] = ['push_sent', 'push_skipped', 'push_failed', 'push_opened']