: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(cdp): skip invalid team ids in shared team lookups (#122365)
Phil Haackfff0f4e763d0
diff --git a/nodejs/src/ai-observability/services/evaluation-manager.service.test.ts b/nodejs/src/ai-observability/services/evaluation-manager.service.test.tsindex d515c5be91ea..0769ee666455 100644--- a/nodejs/src/ai-observability/services/evaluation-manager.service.test.ts+++ b/nodejs/src/ai-observability/services/evaluation-manager.service.test.ts@@ -1,6 +1,7 @@import { closeHub, createHub } from '~/common/utils/db/hub'import { PostgresUse } from '~/common/utils/db/postgres'import { createTeam, createTestTeamFixture } from '~/tests/helpers/sql'+import { INVALID_TEAM_ID_KEYS } from '~/tests/helpers/team'import { Hub } from '~/types'import { insertEvaluation, insertModelConfiguration, insertProviderKey } from '../_tests/fixtures'@@ -182,6 +183,17 @@ describe('EvaluationManagerService', () => {expect(result[teamId2]).toHaveLength(1)})+ it.each(INVALID_TEAM_ID_KEYS)(+ 'returns no evaluations for invalid team id %p without failing the valid team in the same load',+ async (key) => {+ const invalidTeamId = key as unknown as number+ const result = await manager.getEvaluationsForTeams([teamId1, invalidTeamId])++ expect(result[teamId1]).toHaveLength(1)+ expect(result[invalidTeamId]).toEqual([])+ }+ )+it('handles evaluations with bytecode errors', async () => {await insertEvaluation(hub.postgres, teamId1, {name: 'Evaluation with bytecode error',diff --git a/nodejs/src/ai-observability/services/evaluation-manager.service.ts b/nodejs/src/ai-observability/services/evaluation-manager.service.tsindex 578a73ac90d9..2713fd0d94fc 100644--- a/nodejs/src/ai-observability/services/evaluation-manager.service.ts+++ b/nodejs/src/ai-observability/services/evaluation-manager.service.ts@@ -2,6 +2,7 @@ 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'+import { validTeamIds } from '~/common/utils/team-manager'import { Team } from '../../types'import { Evaluation, EvaluationInfo } from '../types'@@ -111,7 +112,7 @@ export class EvaluationManagerService {const response = await this.postgres.query<EvaluationInfo>(PostgresUse.COMMON_READ,`SELECT id, team_id FROM llm_analytics_evaluation WHERE enabled = TRUE AND deleted = FALSE AND team_id = ANY($1)`,- [teamIds],+ [validTeamIds(teamIds)],'fetchAllTeamEvaluations')diff --git a/nodejs/src/ai-observability/services/tagger-manager.service.test.ts b/nodejs/src/ai-observability/services/tagger-manager.service.test.tsindex f1356839fd3f..7eaf5d7f9da4 100644--- a/nodejs/src/ai-observability/services/tagger-manager.service.test.ts+++ b/nodejs/src/ai-observability/services/tagger-manager.service.test.ts@@ -1,6 +1,7 @@import { closeHub, createHub } from '~/common/utils/db/hub'import { PostgresUse } from '~/common/utils/db/postgres'import { createTeam, createTestTeamFixture } from '~/tests/helpers/sql'+import { INVALID_TEAM_ID_KEYS } from '~/tests/helpers/team'import { Hub } from '~/types'import { insertModelConfiguration, insertProviderKey, insertTagger } from '../_tests/fixtures'@@ -165,6 +166,17 @@ describe('TaggerManagerService', () => {expect(result[teamId2]).toHaveLength(1)})+ it.each(INVALID_TEAM_ID_KEYS)(+ 'returns no taggers for invalid team id %p without failing the valid team in the same load',+ async (key) => {+ const invalidTeamId = key as unknown as number+ const result = await manager.getTaggersForTeams([teamId1, invalidTeamId])++ expect(result[teamId1]).toHaveLength(1)+ expect(result[invalidTeamId]).toEqual([])+ }+ )+it('exposes single-tagger getter that returns null for unknown ids', async () => {const known = await manager.getTagger(taggers[0].id)expect(known?.id).toEqual(taggers[0].id)diff --git a/nodejs/src/ai-observability/services/tagger-manager.service.ts b/nodejs/src/ai-observability/services/tagger-manager.service.tsindex 54941c4d1e89..b9915084113d 100644--- a/nodejs/src/ai-observability/services/tagger-manager.service.ts+++ b/nodejs/src/ai-observability/services/tagger-manager.service.ts@@ -2,6 +2,7 @@ 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'+import { validTeamIds } from '~/common/utils/team-manager'import { Team } from '../../types'import { Tagger, TaggerInfo } from '../types'@@ -102,7 +103,7 @@ export class TaggerManagerService {const response = await this.postgres.query<TaggerInfo>(PostgresUse.COMMON_READ,`SELECT id, team_id FROM llm_analytics_tagger WHERE enabled = TRUE AND deleted = FALSE AND team_id = ANY($1)`,- [teamIds],+ [validTeamIds(teamIds)],'fetchAllTeamTaggers')diff --git a/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.test.tsindex 7146216ec594..12bcf0ffaff2 100644--- a/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.test.ts@@ -8,6 +8,7 @@ import { PostgresUse } from '~/common/utils/db/postgres'import { createCdpConsumerDeps } from '~/tests/helpers/cdp'import { forSnapshot } from '~/tests/helpers/snapshots'import { createTestTeamFixture } from '~/tests/helpers/sql'+import { INVALID_TEAM_ID_KEYS } from '~/tests/helpers/team'import { Hub, Team } from '../../types'import { createHogExecutionGlobals, insertHogFunction } from '../_tests/fixtures'@@ -524,6 +525,16 @@ describe('CdpLegacyEventsConsumer', () => {const hogFunctions = await consumer['pluginConfigsLoader'].get('99999')expect(hogFunctions).toEqual([])})++ it.each(INVALID_TEAM_ID_KEYS)(+ 'returns an empty array for invalid team id %p without failing the valid team in the same load',+ async (key) => {+ const result = await consumer['pluginConfigsLoader'].getMany([team.id.toString(), key])++ expect(result[team.id.toString()]?.map((x) => x.pluginConfigId)).toEqual([pluginConfig.id])+ expect(result[key]).toEqual([])+ }+ )})describe('migrated legacy_destination hog functions', () => {diff --git a/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.ts b/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.tsindex 3a60aeebe766..f1f76905095a 100644--- a/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.ts@@ -8,6 +8,7 @@ import { parseJSON } from '~/common/utils/json-parse'import { LazyLoader } from '~/common/utils/lazy-loader'import { logger } from '~/common/utils/logger'import { PromiseScheduler } from '~/common/utils/promise-scheduler'+import { validTeamIds } from '~/common/utils/team-manager'import {HealthCheckResult,@@ -106,6 +107,7 @@ export class CdpLegacyEventsConsumer extends CdpConsumerBase<CdpLegacyEventsCons}private async loadAndBuildHogFunctions(teamIds: string[]): Promise<Record<string, PluginConfigHogFunction[]>> {+ const numericTeamIds = validTeamIds(teamIds)const { rows } = await this.deps.postgres.query(PostgresUse.COMMON_READ,`SELECT@@ -124,7 +126,7 @@ export class CdpLegacyEventsConsumer extends CdpConsumerBase<CdpLegacyEventsConsAND posthog_pluginconfig.enabled = 't'AND (posthog_pluginconfig.deleted IS NULL OR posthog_pluginconfig.deleted != 't')AND posthog_plugin.capabilities->'methods' @> '["onEvent"]'::jsonb`,- [teamIds.map((id) => parseInt(id))],+ [numericTeamIds],'loadPluginConfigHogFunctions')@@ -222,14 +224,11 @@ export class CdpLegacyEventsConsumer extends CdpConsumerBase<CdpLegacyEventsCons}}- return this.preferMigratedHogFunctions(results, await this.loadMigratedHogFunctions(teamIds))+ return this.preferMigratedHogFunctions(results, await this.loadMigratedHogFunctions(numericTeamIds))}- private async loadMigratedHogFunctions(teamIds: string[]): Promise<Record<string, HogFunctionType[]>> {- const byTeam = await this.hogFunctionManager.getHogFunctionsForTeams(- teamIds.map((id) => parseInt(id)),- ['legacy_destination']- )+ private async loadMigratedHogFunctions(teamIds: number[]): Promise<Record<string, HogFunctionType[]>> {+ const byTeam = await this.hogFunctionManager.getHogFunctionsForTeams(teamIds, ['legacy_destination'])return Object.fromEntries(Object.entries(byTeam).map(([teamId, fns]) => [teamId, fns]))}diff --git a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.test.tsindex 4c0cc4e60f87..a2da97b0d4ec 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.test.ts@@ -7,6 +7,7 @@ import { PostgresUse } from '~/common/utils/db/postgres'import { waitForExpect } from '~/tests/helpers/expectations'import { forSnapshot } from '~/tests/helpers/snapshots'import { createTeam, createTestTeamFixture } from '~/tests/helpers/sql'+import { INVALID_TEAM_ID_KEYS } from '~/tests/helpers/team'import { Hub } from '~/types'import { insertHogFlow } from '../../_tests/fixtures-hogflows'@@ -192,6 +193,17 @@ describe('HogFlowManager', () => {expect(result[nonExistentTeamId]).toEqual([])})+ it.each(INVALID_TEAM_ID_KEYS)(+ 'returns no ids for invalid team id %p without failing the valid team in the same load',+ async (key) => {+ const invalidTeamId = key as unknown as number+ const result = await manager.getHogFlowIdsForTeams([teamId1, invalidTeamId])++ expect(result[teamId1]).toHaveLength(2)+ expect(result[invalidTeamId]).toEqual([])+ }+ )+it('handles archived hog flows', async () => {const originalResult = await manager.getHogFlowIdsForTeams([teamId1, teamId2])expect(originalResult[teamId1]).toHaveLength(2)diff --git a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.tsindex ef607f18481d..e4bb9d9ece3f 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.ts@@ -7,6 +7,7 @@ import { DEFAULT_LOADER_RETRY, LazyLoader } from '~/common/utils/lazy-loader'import { logger } from '~/common/utils/logger'import { captureException } from '~/common/utils/posthog'import { PubSub } from '~/common/utils/pubsub'+import { validTeamIds } from '~/common/utils/team-manager'import { Team } from '~/types'import { EncryptedFields } from '../../utils/encryption-utils'@@ -155,7 +156,7 @@ export class HogFlowManagerService {const response = await this.postgres.query<HogFlowTeamInfo>(PostgresUse.COMMON_READ,`SELECT id, team_id, version FROM posthog_hogflow WHERE status='active' AND team_id = ANY($1)`,- [teamIds],+ [validTeamIds(teamIds)],'fetchAllTeamHogFlows')diff --git a/nodejs/src/cdp/services/managers/hog-function-manager.service.test.ts b/nodejs/src/cdp/services/managers/hog-function-manager.service.test.tsindex e378a6f6ef83..47ec204c98e7 100644--- a/nodejs/src/cdp/services/managers/hog-function-manager.service.test.ts+++ b/nodejs/src/cdp/services/managers/hog-function-manager.service.test.ts@@ -5,6 +5,7 @@ import { closeHub, createHub } from '~/common/utils/db/hub'import { PostgresUse } from '~/common/utils/db/postgres'import { forSnapshot } from '~/tests/helpers/snapshots'import { createTeam, createTestTeamFixture } from '~/tests/helpers/sql'+import { INVALID_TEAM_ID_KEYS } from '~/tests/helpers/team'import { Hub } from '~/types'import { insertHogFunction } from '../../_tests/fixtures'@@ -161,6 +162,13 @@ describe('HogFunctionManager', () => {])})+ it("keeps a team's hog functions when a fractional id of that team shares the load", async () => {+ const result = await manager.getHogFunctionsForTeams([teamId1, teamId1 + 0.5], ['destination'])++ expect(result[teamId1].map((fn) => fn.id)).toEqual([hogFunctions[0].id])+ expect(result[teamId1 + 0.5]).toEqual([])+ })+describe('filters hog functions by type', () => {it('for just transformations', async () => {expect((await manager.getHogFunctionsForTeam(teamId1, ['transformation'])).length).toEqual(1)@@ -207,6 +215,20 @@ describe('HogFunctionManager', () => {expect(result[nonExistentTeamId]).toEqual([])})+ it.each(INVALID_TEAM_ID_KEYS)(+ 'returns no ids for invalid team id %p without failing the valid team in the same load',+ async (key) => {+ const invalidTeamId = key as unknown as number+ const result = await manager.getHogFunctionIdsForTeams(+ [teamId1, invalidTeamId],+ ['destination', 'transformation']+ )++ expect(result[teamId1]).toHaveLength(2)+ expect(result[invalidTeamId]).toEqual([])+ }+ )+it('filters by specific type correctly', async () => {const result = await manager.getHogFunctionIdsForTeams([teamId1], ['transformation'])diff --git a/nodejs/src/cdp/services/managers/hog-function-manager.service.ts b/nodejs/src/cdp/services/managers/hog-function-manager.service.tsindex a54628e5a471..412993a4b32f 100644--- a/nodejs/src/cdp/services/managers/hog-function-manager.service.ts+++ b/nodejs/src/cdp/services/managers/hog-function-manager.service.ts@@ -4,6 +4,7 @@ import { DEFAULT_LOADER_RETRY, LazyLoader, LoadOptions } from '~/common/utils/laimport { logger } from '~/common/utils/logger'import { captureException } from '~/common/utils/posthog'import { PubSub } from '~/common/utils/pubsub'+import { validTeamIds } from '~/common/utils/team-manager'import { Team } from '../../../types'import { HogFunctionType, HogFunctionTypeType } from '../../types'@@ -119,11 +120,7 @@ export class HogFunctionManagerService {result[fn.team_id].push(fn)}- for (const [teamId, fns] of Object.entries(result)) {- result[parseInt(teamId)] = sortHogFunctions(fns)- }-- return result+ return Object.fromEntries(Object.entries(result).map(([teamId, fns]) => [teamId, sortHogFunctions(fns)]))}public async getHogFunctionIdsForTeams(@@ -196,7 +193,7 @@ export class HogFunctionManagerService {const response = await this.postgres.query<Pick<HogFunctionType, 'id' | 'team_id' | 'type'>>(PostgresUse.COMMON_READ,`SELECT id, team_id, type FROM posthog_hogfunction WHERE enabled = TRUE AND deleted = FALSE AND team_id = ANY($1)`,- [teamIds],+ [validTeamIds(teamIds)],'fetchAllTeamHogFunctions')diff --git a/nodejs/src/cdp/services/managers/persons-manager.service.test.ts b/nodejs/src/cdp/services/managers/persons-manager.service.test.tsindex f6a66e4a5379..1ae43824d3a6 100644--- a/nodejs/src/cdp/services/managers/persons-manager.service.test.ts+++ b/nodejs/src/cdp/services/managers/persons-manager.service.test.ts@@ -14,6 +14,7 @@ import {} from '~/common/generated/personhog/personhog/types/v1/person_pb'import { PersonHogClient } from '~/common/personhog/client'import { PersonHogPersonReadRepository } from '~/common/personhog/personhog-person-read-repository'+import { INVALID_TEAM_ID_KEYS } from '~/tests/helpers/team'import { PersonsManagerService } from './persons-manager.service'@@ -326,6 +327,24 @@ describe('PersonsManagerService', () => {})})+ it.each(+ INVALID_TEAM_ID_KEYS.flatMap((key) => [+ [key, 'distinct_id', 'distinct_id_A_1'] as const,+ [key, 'person_id', TEST_PERSONS[0].uuid] as const,+ ])+ )(+ 'returns null for invalid team id %p by %s without failing the valid team in the same load',+ async (key, kind, id) => {+ const [valid, invalid] = await Promise.all([+ manager.getCyclotronPerson(TEAM_1, id, kind),+ manager.getCyclotronPerson(key as unknown as number, id, kind),+ ])++ expect(valid?.properties).toEqual({ foo: '1' })+ expect(invalid).toBeNull()+ }+ )+describe('error handling', () => {it('propagates errors when personhog is unavailable', async () => {const failingTransport = createRouterTransport(({ service }) => {diff --git a/nodejs/src/cdp/services/managers/persons-manager.service.ts b/nodejs/src/cdp/services/managers/persons-manager.service.tsindex e9ca215f58e4..6d14658a9065 100644--- a/nodejs/src/cdp/services/managers/persons-manager.service.ts+++ b/nodejs/src/cdp/services/managers/persons-manager.service.ts@@ -1,7 +1,7 @@import { PersonReadRepository } from '~/common/persons/repositories/person-repository'import { LazyLoader } from '~/common/utils/lazy-loader'import { logger } from '~/common/utils/logger'-import { TeamManager } from '~/common/utils/team-manager'+import { TeamManager, isValidTeamId } from '~/common/utils/team-manager'import { CyclotronPerson } from '../../types'import { getPersonDisplayName } from '../../utils'@@ -15,9 +15,12 @@ const toKey = (args: PersonGetArgs): string => `${args.teamId}:${args.id}`const fromKey = (key: string): PersonGetArgs => {const [teamId, ...idParts] = key.split(':')- return { teamId: parseInt(teamId), id: idParts.join(':') }+ return { teamId: Number(teamId), id: idParts.join(':') }}+const fromValidKeys = (keys: string[]): PersonGetArgs[] =>+ keys.map(fromKey).filter(({ teamId }) => isValidTeamId(teamId))+export type PersonManagerPerson = {id: stringproperties: Record<string, any>@@ -94,7 +97,7 @@ export class PersonsManagerService {private async fetchPersonsByDistinctIds(ids: string[]): Promise<Record<string, PersonManagerPersonWithDistinctId | undefined>> {- const teamPersons = ids.map(fromKey)+ const teamPersons = fromValidKeys(ids)logger.debug('[PersonManager]', 'Fetching persons', { teamPersons })@@ -121,7 +124,7 @@ export class PersonsManagerService {}private async fetchPersonsByPersonIds(ids: string[]): Promise<Record<string, PersonManagerPerson | undefined>> {- const teamPersons = ids.map(fromKey)+ const teamPersons = fromValidKeys(ids)logger.debug('[PersonManager]', 'Fetching persons', { teamPersons })diff --git a/nodejs/src/cdp/services/managers/recipients-manager.service.test.ts b/nodejs/src/cdp/services/managers/recipients-manager.service.test.tsindex 2a75d7c444d7..18b185d3b266 100644--- a/nodejs/src/cdp/services/managers/recipients-manager.service.test.ts+++ b/nodejs/src/cdp/services/managers/recipients-manager.service.test.ts@@ -2,6 +2,7 @@ import { closeHub, createHub } from '~/common/utils/db/hub'import { PostgresUse } from '~/common/utils/db/postgres'import { UUIDT } from '~/common/utils/utils'import { createTeam, createTestTeamFixture, getTeam } from '~/tests/helpers/sql'+import { INVALID_TEAM_ID_KEYS } from '~/tests/helpers/team'import { Hub, Team } from '~/types'import { RecipientGetArgs, RecipientsManagerService } from './recipients-manager.service'@@ -139,6 +140,24 @@ describe('RecipientsManager', () => {const results = await manager.getMany([])expect(results).toEqual({})})++ it.each(INVALID_TEAM_ID_KEYS)(+ 'returns null for invalid team id %p without failing the valid team in the same load',+ async (key) => {+ await createRecipient(team.id, '[email protected]', { 'cat-1': 'OPTED_IN' })+ const invalidTeamId = key as unknown as number++ const results = await manager.getMany([+ { teamId: team.id, identifier: '[email protected]' },+ { teamId: invalidTeamId, identifier: '[email protected]' },+ ])++ expect(results[`${team.id}:[email protected]`]?.preferences).toEqual({ 'cat-1': 'OPTED_IN' })+ expect(results[`${key}:[email protected]`]).toBeNull()+ // A load that holds only invalid ids has no query to run.+ expect(await manager.get({ teamId: invalidTeamId, identifier: '[email protected]' })).toBeNull()+ }+ )})describe('getPreference', () => {diff --git a/nodejs/src/cdp/services/managers/recipients-manager.service.ts b/nodejs/src/cdp/services/managers/recipients-manager.service.tsindex 1b3520babcf7..f44185c6bd3d 100644--- a/nodejs/src/cdp/services/managers/recipients-manager.service.ts+++ b/nodejs/src/cdp/services/managers/recipients-manager.service.ts@@ -1,6 +1,7 @@import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'import { LazyLoader } from '~/common/utils/lazy-loader'import { logger } from '~/common/utils/logger'+import { isValidTeamId } from '~/common/utils/team-manager'export type RecipientGetArgs = {teamId: number@@ -11,7 +12,7 @@ const toKey = (args: RecipientGetArgs): string => `${args.teamId}:${args.identifconst fromKey = (key: string): RecipientGetArgs => {const [teamId, identifier] = key.split(':', 2)- return { teamId: parseInt(teamId), identifier }+ return { teamId: Number(teamId), identifier }}export type PreferenceStatus = 'OPTED_IN' | 'OPTED_OUT' | 'NO_PREFERENCE'@@ -121,7 +122,10 @@ export class RecipientsManagerService {}private async fetchRecipients(ids: string[]): Promise<Record<string, RecipientManagerRecipient | undefined>> {- const recipientArgs = ids.map(fromKey)+ const recipientArgs = ids.map(fromKey).filter(({ teamId }) => isValidTeamId(teamId))+ if (recipientArgs.length === 0) {+ return {}+ }logger.debug('[RecipientsManager]', 'Fetching recipients', { recipientArgs })diff --git a/nodejs/src/cdp/services/managers/team-workflows-config.service.ts b/nodejs/src/cdp/services/managers/team-workflows-config.service.tsindex b725198f5b19..c32434562bde 100644--- a/nodejs/src/cdp/services/managers/team-workflows-config.service.ts+++ b/nodejs/src/cdp/services/managers/team-workflows-config.service.ts@@ -2,6 +2,7 @@ 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'+import { validTeamIds } from '~/common/utils/team-manager'// Mirrors EmailTrackingConsentMode in products/workflows/backend/models/team_workflows_config.pyexport type EmailTrackingConsentMode = 'off' | 'opt_out' | 'opt_in'@@ -141,7 +142,7 @@ export class TeamWorkflowsConfigService {email_sending_tier, marketing_frequency_cap_max_messages, marketing_frequency_cap_window_daysFROM workflows_teamworkflowsconfigWHERE team_id = ANY($1)`,- [teamIds.map(Number)],+ [validTeamIds(teamIds)],'fetch-team-workflows-configs')diff --git a/nodejs/src/cdp/services/messaging/email-suppression.service.test.ts b/nodejs/src/cdp/services/messaging/email-suppression.service.test.tsindex 6bf1d8dfb400..820c15f12ee8 100644--- a/nodejs/src/cdp/services/messaging/email-suppression.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email-suppression.service.test.ts@@ -1,6 +1,7 @@import { closeHub, createHub } from '~/common/utils/db/hub'import { PostgresUse } from '~/common/utils/db/postgres'import { createTeam, createTestTeamFixture } from '~/tests/helpers/sql'+import { INVALID_TEAM_ID_KEYS } from '~/tests/helpers/team'import { Hub, Team } from '~/types'import { EmailSuppressionService, emailSuppressionConfigFromEnv } from './email-suppression.service'@@ -360,5 +361,31 @@ describe('EmailSuppressionService', () => {expect(await svc.isSuppressed(team.id, email)).toBe(expected)})++ // isSuppressed fails open. A load that throws would therefore let a suppressed address receive mail.+ it.each(INVALID_TEAM_ID_KEYS)(+ 'keeps an address suppressed when invalid team id %p shares its load',+ async (key) => {+ const svc = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ const email = '[email protected]'+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO posthog_messagesuppression+ (id, team_id, identifier, source, reason, transient_bounce_count,+ suppressed, suppressed_at, deleted, created_at, updated_at)+ VALUES (gen_random_uuid(), $1, $2, 'BOUNCE', 'test row', 5,+ true, NOW(), false, NOW(), NOW())`,+ [team.id, email],+ 'test-insert-suppression'+ )++ const results = await Promise.all([+ svc.isSuppressed(team.id, email),+ svc.isSuppressed(key as unknown as number, email),+ ])++ expect(results).toEqual([true, false])+ }+ )})})diff --git a/nodejs/src/cdp/services/messaging/email-suppression.service.ts b/nodejs/src/cdp/services/messaging/email-suppression.service.tsindex e8ee9bf1c879..b7d9561928b7 100644--- a/nodejs/src/cdp/services/messaging/email-suppression.service.ts+++ b/nodejs/src/cdp/services/messaging/email-suppression.service.ts@@ -3,6 +3,7 @@ import { Counter } from 'prom-client'import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'import { LazyLoader } from '~/common/utils/lazy-loader'import { logger } from '~/common/utils/logger'+import { isValidTeamId } from '~/common/utils/team-manager'const cdpEmailSuppressionTotal = new Counter({name: 'cdp_email_suppression_total',@@ -346,7 +347,7 @@ export class EmailSuppressionService {// stored identifier is an email so split on the first ':' only.const parsed = keys.map((key) => {const idx = key.indexOf(':')- return { key, teamId: parseInt(key.slice(0, idx), 10), identifier: key.slice(idx + 1) }+ return { key, teamId: Number(key.slice(0, idx)), identifier: key.slice(idx + 1) }})// Group by team_id so we run one indexed `identifier = ANY(...)` scan per team instead of an@@ -356,6 +357,9 @@ export class EmailSuppressionService {// always a single query regardless of batch size.const byTeam = new Map<number, string[]>()for (const p of parsed) {+ if (!isValidTeamId(p.teamId)) {+ continue+ }const list = byTeam.get(p.teamId) ?? []list.push(p.identifier)byTeam.set(p.teamId, list)diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.tsindex d958223b0637..dcc3675ccecd 100644--- a/nodejs/src/cdp/services/messaging/email.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts@@ -14,6 +14,7 @@ import { closeHub, createHub } from '~/common/utils/db/hub'import { PostgresUse } from '~/common/utils/db/postgres'import { waitForExpect } from '~/tests/helpers/expectations'import { createTestTeamFixture } from '~/tests/helpers/sql'+import { INVALID_TEAM_ID_KEYS } from '~/tests/helpers/team'import { Hub, Team } from '../../../types'import { RecipientsManagerService } from '../managers/recipients-manager.service'@@ -1310,6 +1311,23 @@ describe('EmailService', () => {}, 3000)})+ // The suspension check fails open. A load that throws would therefore let a suspended team send.+ it.each(INVALID_TEAM_ID_KEYS)(+ 'keeps a suspended team blocked when invalid team id %p shares its config load',+ async (key) => {+ await suspendTeam()+ const configService = new TeamWorkflowsConfigService(hub.postgres, hub.pubSub)++ const [suspension, invalidTeamConfig] = await Promise.all([+ configService.getEmailSendingSuspension(team.id),+ configService.get(key as unknown as number),+ ])++ expect(suspension).toEqual('staff')+ expect(invalidTeamConfig).toMatchObject({ email_sending_suspended: false })+ }+ )+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/common/utils/event-schema-enforcement-manager.test.ts b/nodejs/src/common/utils/event-schema-enforcement-manager.test.tsindex 50379a4abf41..17071fdc0715 100644--- a/nodejs/src/common/utils/event-schema-enforcement-manager.test.ts+++ b/nodejs/src/common/utils/event-schema-enforcement-manager.test.ts@@ -1,4 +1,5 @@import { createTeam, createTestTeamFixture } from '~/tests/helpers/sql'+import { INVALID_TEAM_ID_KEYS } from '~/tests/helpers/team'import { Hub, Team } from '~/types'import { defaultConfig } from '../config/config'@@ -233,6 +234,18 @@ describe('EventSchemaEnforcementManager', () => {expect(result['99999'].size).toBe(0)})+ it.each(INVALID_TEAM_ID_KEYS)(+ 'returns an empty Map for invalid team id %p without failing the valid team in the same load',+ async (key) => {+ await createEnforcedSchema(teamId, 'event_1', [{ name: 'prop1', type: 'String', required: true }])++ const result = await schemaManager.getSchemasForTeams([teamId, key as unknown as number])++ expect(result[String(teamId)].size).toBe(1)+ expect(result[key].size).toBe(0)+ }+ )+it('efficiently loads multiple teams in single query', async () => {await createEnforcedSchema(teamId, 'test_event', [{ name: 'prop', type: 'String', required: true }])diff --git a/nodejs/src/common/utils/event-schema-enforcement-manager.ts b/nodejs/src/common/utils/event-schema-enforcement-manager.tsindex e34803fc2047..e598f833ec56 100644--- a/nodejs/src/common/utils/event-schema-enforcement-manager.ts+++ b/nodejs/src/common/utils/event-schema-enforcement-manager.ts@@ -2,6 +2,7 @@ import { EventSchemaEnforcement } from '~/types'import { PostgresRouter, PostgresUse } from './db/postgres'import { LazyLoader, LoadOptions, LoaderRetryOptions } from './lazy-loader'+import { validTeamIds } from './team-manager'/*** Raw row from the database query - one row per property per event.@@ -67,7 +68,7 @@ export class EventSchemaEnforcementManager {}private async fetchSchemas(teamIds: string[]): Promise<Record<string, EventSchemaMap | null>> {- const numericTeamIds = teamIds.map(Number).filter((id) => !isNaN(id) && id > 0)+ const numericTeamIds = validTeamIds(teamIds)if (numericTeamIds.length === 0) {const result: Record<string, EventSchemaMap | null> = {}diff --git a/nodejs/src/common/utils/team-manager.ts b/nodejs/src/common/utils/team-manager.tsindex 83005264a89d..f8009e162ffb 100644--- a/nodejs/src/common/utils/team-manager.ts+++ b/nodejs/src/common/utils/team-manager.ts@@ -17,6 +17,11 @@ export function isValidTeamId(value: unknown): value is number {return Number.isInteger(value) && (value as number) > 0 && (value as number) <= 2_147_483_647}+export function validTeamIds(keys: string[]): number[] {+ // parseInt would read "1.5" as team 1. Number keeps it 1.5, which isValidTeamId rejects.+ return keys.map(Number).filter(isValidTeamId)+}+export interface TeamManagerOptions {/** Retry transient team-load failures (e.g. a Postgres pooler blip) instead of letting them propagate. */loaderRetry?: LoaderRetryOptionsdiff --git a/nodejs/tests/helpers/team.ts b/nodejs/tests/helpers/team.tsindex 3f9780a19afe..801f3551d1f1 100644--- a/nodejs/tests/helpers/team.ts+++ b/nodejs/tests/helpers/team.ts@@ -1,5 +1,7 @@import { FlagEvaluationsMode, ProjectId, Team } from '../../src/types'+export const INVALID_TEAM_ID_KEYS = ['abc', '1.5', '3000000000', '0', '-1', '', 'undefined', 'NaN']+/*** Helper function to create a Team object for tests with sensible defaults.*