: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): block email sends while the SES tenant is paused (#90018)
Daniel Marchukb91321a5e94e
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex f7f9e4867ad9..047dda0e1524 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -397,7 +397,7 @@ export function createCdpCoreServices()const trackingCodeSigner = new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL)- const teamWorkflowsConfigService = new TeamWorkflowsConfigService(deps.postgres)+ const teamWorkflowsConfigService = new TeamWorkflowsConfigService(deps.postgres, deps.pubSub)const outputs = createCdpOutputsRegistry().build(deps.cdpProducerRegistry, config)const messageAssetsService = new MessageAssetsService(outputs)// Constructed here (rather than below with the other messaging services) so it can be threadeddiff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.tsindex 723ba4998c9c..5fb256be6188 100644--- a/nodejs/src/cdp/services/hog-executor.service.test.ts+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts@@ -75,7 +75,7 @@ describe('Hog Executor', () => {sesUntrackedConfigurationSet: hub.SES_UNTRACKED_CONFIGURATION_SET,},hub.integrationManager,- new TeamWorkflowsConfigService(hub.postgres),+ new TeamWorkflowsConfigService(hub.postgres, hub.pubSub),hub.ENCRYPTION_SALT_KEYS,hub.SITE_URL,new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.tsindex 29971ba35d97..4d05e19b77c7 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts@@ -64,7 +64,7 @@ describe('HogFunctionHandler', () => {sesUntrackedConfigurationSet: hub.SES_UNTRACKED_CONFIGURATION_SET,},hub.integrationManager,- new TeamWorkflowsConfigService(hub.postgres),+ new TeamWorkflowsConfigService(hub.postgres, hub.pubSub),hub.ENCRYPTION_SALT_KEYS,hub.SITE_URL,new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.tsindex 5a25a6118638..5c3f39356e37 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts@@ -85,7 +85,7 @@ describe('Hogflow Executor', () => {sesUntrackedConfigurationSet: hub.SES_UNTRACKED_CONFIGURATION_SET,},hub.integrationManager,- new TeamWorkflowsConfigService(hub.postgres),+ new TeamWorkflowsConfigService(hub.postgres, hub.pubSub),hub.ENCRYPTION_SALT_KEYS,hub.SITE_URL,new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),diff --git a/nodejs/src/cdp/services/managers/team-workflows-config.service.ts b/nodejs/src/cdp/services/managers/team-workflows-config.service.tsindex 06e4fafeaa48..e7c93cb12131 100644--- a/nodejs/src/cdp/services/managers/team-workflows-config.service.ts+++ b/nodejs/src/cdp/services/managers/team-workflows-config.service.ts@@ -1,20 +1,29 @@import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'import { LazyLoader } from '~/common/utils/lazy-loader'import { logger } from '~/common/utils/logger'+import { PubSub } from '~/common/utils/pubsub'// Mirrors EmailTrackingConsentMode in products/workflows/backend/models/team_workflows_config.pyexport type EmailTrackingConsentMode = 'off' | 'opt_out' | 'opt_in'+/**+ * Which switch blocks workflow email for a team. `staff` is our own kill switch; `provider` is+ * a paused AWS SES tenant, mirrored into the config row by the workflows backend.+ */+export type EmailSendingSuspensionCause = 'staff' | 'provider'+export type TeamWorkflowsConfig = {capture_workflows_engagement_events: booleanemail_tracking_consent_mode: EmailTrackingConsentModeemail_sending_suspended: boolean+ ses_tenant_provider_suspended: boolean}const DEFAULT_CONFIG: TeamWorkflowsConfig = {capture_workflows_engagement_events: false,email_tracking_consent_mode: 'off',email_sending_suspended: false,+ ses_tenant_provider_suspended: false,}/**@@ -25,13 +34,22 @@ const DEFAULT_CONFIG: TeamWorkflowsConfig = {export class TeamWorkflowsConfigService {private lazyLoader: LazyLoader<TeamWorkflowsConfig>- constructor(private postgres: PostgresRouter) {+ constructor(+ private postgres: PostgresRouter,+ pubSub: PubSub+ ) {this.lazyLoader = new LazyLoader({name: 'team_workflows_config',refreshAgeMs: 2 * 60 * 1000,refreshJitterMs: 30 * 1000,loader: async (teamIds) => await this.fetchConfigs(teamIds),})+ // The refresh age alone would leave a team the provider paused still sending, and a+ // reinstated team still blocked, until its entry expired. The provider state sync announces+ // each change so the next send reads it. Staff kill-switch flips still wait out the age.+ pubSub.on<{ teamId: number }>('reload-team-workflows-config', ({ teamId }) => {+ this.lazyLoader.markForRefresh(String(teamId))+ })}public async get(teamId: number): Promise<TeamWorkflowsConfig> {@@ -49,16 +67,24 @@ export class TeamWorkflowsConfigService {}/**- * 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.+ * Which switch, if any, blocks workflow email for this team: the kill switch staff set when a+ * team's sender reputation puts shared SES deliverability at risk, or the team's AWS SES tenant+ * being paused by AWS. Returns null when sending is allowed. Fails open: a lookup error must+ * never block legitimate sends.*/- public async isEmailSendingSuspended(teamId: number): Promise<boolean> {+ public async getEmailSendingSuspension(teamId: number): Promise<EmailSendingSuspensionCause | null> {try {const config = await this.get(teamId)- return config.email_sending_suspended+ if (config.email_sending_suspended) {+ return 'staff'+ }+ if (config.ses_tenant_provider_suspended) {+ return 'provider'+ }+ return null} catch (error) {logger.error('[TeamWorkflowsConfig] Failed to check email sending suspension', { teamId, error })- return false+ return null}}@@ -68,10 +94,14 @@ export class TeamWorkflowsConfigService {capture_workflows_engagement_events: booleanemail_tracking_consent_mode: EmailTrackingConsentModeemail_sending_suspended: boolean+ ses_tenant_provider_suspended: boolean}>(PostgresUse.COMMON_READ,+ // Only DISABLED blocks: ENABLED and REINSTATED both permit sending, and '' means the+ // tenant state has never been synced for this team.`SELECT team_id, capture_workflows_engagement_events, email_tracking_consent_mode,- email_sending_suspended_at IS NOT NULL AS email_sending_suspended+ email_sending_suspended_at IS NOT NULL AS email_sending_suspended,+ ses_tenant_sending_status = 'DISABLED' AS ses_tenant_provider_suspendedFROM workflows_teamworkflowsconfigWHERE team_id = ANY($1)`,[teamIds.map(Number)],@@ -87,6 +117,7 @@ export class TeamWorkflowsConfigService {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,+ ses_tenant_provider_suspended: row.ses_tenant_provider_suspended,}}return configsdiff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.tsindex e532bdeff8bf..ddbbb30752bf 100644--- a/nodejs/src/cdp/services/messaging/email.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts@@ -107,7 +107,7 @@ describe('EmailService', () => {sesUntrackedConfigurationSet: hub.SES_UNTRACKED_CONFIGURATION_SET,},hub.integrationManager,- new TeamWorkflowsConfigService(hub.postgres),+ new TeamWorkflowsConfigService(hub.postgres, hub.pubSub),hub.ENCRYPTION_SALT_KEYS,hub.SITE_URL,new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),@@ -131,7 +131,7 @@ describe('EmailService', () => {sesUntrackedConfigurationSet: '',},hub.integrationManager,- new TeamWorkflowsConfigService(hub.postgres),+ new TeamWorkflowsConfigService(hub.postgres, hub.pubSub),hub.ENCRYPTION_SALT_KEYS,hub.SITE_URL,new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),@@ -486,7 +486,7 @@ describe('EmailService', () => {sesUntrackedConfigurationSet: hub.SES_UNTRACKED_CONFIGURATION_SET,},hub.integrationManager,- new TeamWorkflowsConfigService(hub.postgres),+ new TeamWorkflowsConfigService(hub.postgres, hub.pubSub),hub.ENCRYPTION_SALT_KEYS,hub.SITE_URL,new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),@@ -750,10 +750,10 @@ describe('EmailService', () => {})describe('team suspension enforcement at send time', () => {- // Guards the reputation kill switch: while a team is suspended, no send path may+ // Guards both suspension switches: 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.+ // These write a real config row so they also cover the service's SELECT; mocking+ // getEmailSendingSuspension would pass with the column missing from the query.const suspendTeam = async (): Promise<void> => {await hub.postgres.query(PostgresUse.COMMON_WRITE,@@ -788,6 +788,55 @@ describe('EmailService', () => {expect(result.metrics).toEqual([])})+ const setProviderTenantStatus = async (status: string): Promise<void> => {+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ // email_sending_suspension_reason is NOT NULL and its default is Django-side,+ // not on the column, so a raw INSERT has to supply it.+ `INSERT INTO workflows_teamworkflowsconfig+ (team_id, capture_workflows_engagement_events, email_tracking_consent_mode,+ email_sending_suspension_reason, ses_tenant_sending_status)+ VALUES ($1, false, 'off', '', $2)+ ON CONFLICT (team_id) DO UPDATE SET ses_tenant_sending_status = $2`,+ [team.id, status],+ 'test-set-ses-tenant-sending-status'+ )+ }++ // A paused provider tenant rejects every send, so the send path has to read the stored+ // state. Only DISABLED blocks: REINSTATED is what a tenant the provider has restored+ // reads, so treating any non-ENABLED status as paused would withhold accepted sends.+ it.each([+ ['DISABLED', 0, 'email_suspended'],+ ['REINSTATED', 1, 'email_sent'],+ ])('provider tenant status %s: %i SES calls, records %s', async (status, sesCalls, metricName) => {+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })+ await setProviderTenantStatus(status as string)++ const result = await service.executeSendEmail(invocation)++ expect(sendEmailSpy).toHaveBeenCalledTimes(sesCalls as number)+ expect(result.metrics.map((m) => m.metric_name)).toContain(metricName)+ })++ // The send path caches this row for minutes, so a pause that lands after the first read+ // would keep sending — and a reinstatement would keep blocking — until the entry aged+ // out. The provider state sync announces each change to close that window.+ it('picks up a provider status change announced while the config is cached', async () => {+ const configService = new TeamWorkflowsConfigService(hub.postgres, hub.pubSub)+ await setProviderTenantStatus('ENABLED')+ expect(await configService.getEmailSendingSuspension(team.id)).toBeNull()++ await setProviderTenantStatus('DISABLED')++ await waitForExpect(async () => {+ // Republished every poll: subscribing is asynchronous, so the first publish can+ // land before this subscriber is listening. Marking for refresh is idempotent.+ await hub.pubSub.publish('reload-team-workflows-config', JSON.stringify({ teamId: team.id }))+ expect(await configService.getEmailSendingSuspension(team.id)).toEqual('provider')+ }, 3000)+ })+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.diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.tsindex 26d49d158047..e0f1e28ac7d5 100644--- a/nodejs/src/cdp/services/messaging/email.service.ts+++ b/nodejs/src/cdp/services/messaging/email.service.ts@@ -229,12 +229,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')+ // Team-level kill switches: staff suspend all workflow email for a team whose sender+ // reputation endangers shared SES deliverability, and AWS pauses the team's SES tenant+ // for the same underlying reason. Same choke-point placement as the suppression check+ // below so no upstream route can bypass either. Test sends are blocked too — they hit+ // SES and count against the tenant all the same. A paused tenant rejects every send, so+ // gating here turns wasted invocations into one clear skip.+ const suspensionCause = await this.teamWorkflowsConfigService.getEmailSendingSuspension(invocation.teamId)+ if (suspensionCause) {+ addLog(+ 'warn',+ suspensionCause === 'staff'+ ? 'Skipping send: email sending is suspended for this project. Contact support to get sending re-enabled.'+ : 'Skipping send: our email provider paused sending for this project. Check the Reputation tab to see what to fix.'+ )+ logger.warn('Skipping email send for a suspended team', {+ teamId: invocation.teamId,+ cause: suspensionCause,+ })+ // One metric for both causes: from the project's side sending is off either way, so+ // the cause belongs in the log lines above and not in a second metric name.if (!isTest) {result.metrics.push({team_id: invocation.teamId,diff --git a/posthog/plugins/plugin_server_api.py b/posthog/plugins/plugin_server_api.pyindex 4e54b289ad4b..4c4cbd3dc08e 100644--- a/posthog/plugins/plugin_server_api.py+++ b/posthog/plugins/plugin_server_api.py@@ -76,6 +76,11 @@ def reload_integrations_on_workers(team_id: int, integration_ids: list[int]):publish_message("reload-integrations", {"teamId": team_id, "integrationIds": integration_ids})+def reload_team_workflows_config_on_workers(team_id: int):+ logger.info(f"Reloading team workflows config for team {team_id} on workers")+ publish_message("reload-team-workflows-config", {"teamId": team_id})++def populate_plugin_capabilities_on_workers(plugin_id: str):logger.info(f"Populating plugin capabilities for plugin {plugin_id} on workers")publish_message("populate-plugin-capabilities", {"pluginId": plugin_id})diff --git a/products/workflows/backend/services/ses_tenant_state.py b/products/workflows/backend/services/ses_tenant_state.pyindex 6360be32c024..99f9f5c3c3de 100644--- a/products/workflows/backend/services/ses_tenant_state.py+++ b/products/workflows/backend/services/ses_tenant_state.py@@ -7,6 +7,7 @@ from django.utils import timezoneimport structlogfrom posthog.models.team import Team+from posthog.plugins.plugin_server_api import reload_team_workflows_config_on_workersfrom posthog.tasks.email import (send_email_sending_reputation_finding,send_email_sending_suspended,@@ -45,6 +46,18 @@ _FINDING_DESCRIPTIONS = {_STATE_FIELDS = ["ses_tenant_sending_status", "ses_tenant_reputation_impact", "ses_tenant_state_synced_at"]+def _announce_state_change(team_id: int) -> None:+ """+ Tell the send path to drop its cached copy of the row. Best effort: it re-reads within a couple+ of minutes anyway, so a Redis blip must not fail a webhook or sweep whose state change has+ already committed — the retry would find the state unchanged and never announce it at all.+ """+ try:+ reload_team_workflows_config_on_workers(team_id)+ except Exception:+ logger.exception("Failed to announce SES tenant state change to workers", team_id=team_id)++def sync_ses_tenant_state(team_id: int, provider: SESProvider | None = None, *, verify_team: bool = True) -> None:"""Fetch the authoritative AWS SES tenant state for a team and apply it. Called from the@@ -113,6 +126,11 @@ def apply_ses_tenant_state(to_impact=impact,)+ # The send path caches this row for a couple of minutes, so without this a pause keeps+ # sending and a reinstatement keeps blocking until the entry expires. After commit, so the+ # worker cannot re-read the row before the new state is visible and cache it again.+ transaction.on_commit(lambda: _announce_state_change(team_id))+notify = _pick_notification(previous_status=previous_status,previous_impact=previous_impact,