: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
feat(cdp): mint scoped JWTs for account actions (#90917)
Patricio20d13634541e
diff --git a/nodejs/src/cdp/async-function-registry.ts b/nodejs/src/cdp/async-function-registry.tsindex a4ad0717fbad..a470438ca108 100644--- a/nodejs/src/cdp/async-function-registry.ts+++ b/nodejs/src/cdp/async-function-registry.ts@@ -17,6 +17,7 @@ export type AsyncFunctionContext = {// Contour blocks from the public internet. Only first-party handlers may call it.internalApiBaseUrl: stringconversationsTicketsJwt: ScopedServiceJwt+ customerAnalyticsAccountsJwt: ScopedServiceJwt// Handlers that do real inline I/O without ever setting queueParameters (so the executor's// own queued-type counting never sees them, see internal-api-call.ts) must call this once// per invocation to share the same per-dequeue async-work budget queued calls are capped by.diff --git a/nodejs/src/cdp/async-functions/customer_analytics.ts b/nodejs/src/cdp/async-functions/customer_analytics.tsindex c6504be87dae..9cf149586867 100644--- a/nodejs/src/cdp/async-functions/customer_analytics.ts+++ b/nodejs/src/cdp/async-functions/customer_analytics.ts@@ -3,11 +3,57 @@ import { DateTime } from 'luxon'import { CyclotronInvocationQueueParametersFetchSchema } from '~/cdp/schema/cyclotron'import { HogFlow } from '~/cdp/schema/hogflow'-import { registerAsyncFunction } from '../async-function-registry'+import { AsyncFunctionContext, registerAsyncFunction } from '../async-function-registry'+import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult } from '../types'+import { callInternalApi } from './internal-api-call'import { getTeamWithSecretToken } from './secret-api-token'const ACCOUNT_ACTIONS = 'account workflow actions'+/**+ * Calls the JWT-only internal account routes (products/customer_analytics/backend/+ * presentation/views/internal.py). The token pins the invocation's own team plus this one+ * account's external_id; Django refuses it anywhere else. Used whenever+ * CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET is provisioned — the legacy secret_api_token path+ * below it is the fallback until then (#82564).+ */+async function callInternalAccountApi(+ context: AsyncFunctionContext,+ result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,+ externalId: string,+ options: {+ method: 'GET' | 'PATCH' | 'POST'+ subpath?: string+ body?: string+ extraHeaders?: Record<string, string>+ }+): Promise<void> {+ const { method, subpath = '', body, extraHeaders } = options+ // The external_id is Hog-controlled free text. It travels in the query string (GET) or+ // the JSON body, never a URL path segment, so no format constraint applies — the claim+ // just has to carry the same raw value Django reads from the request.+ const base = `/api/projects/${context.invocation.teamId}/internal/customer_analytics/account${subpath}` as const+ const path = method === 'GET' ? `${base}?external_id=${encodeURIComponent(externalId)}` : base+ await callInternalApi(context, result, {+ jwt: context.customerAnalyticsAccountsJwt,+ path: path as `/${string}`,+ entityClaims: { external_id: externalId },+ method,+ body,+ extraHeaders,+ })+}++// Present only when running inside a HogFlow (spread onto the synthesized invocation);+// forwarded so account activity can attribute writes to the workflow. Only the id is sent —+// the display name is resolved from the workflow on the frontend so it can't be spoofed+// through this header. Typed as an optional HogFlow so a rename of its id shape breaks+// compilation here.+function hogFlowHeaders(context: AsyncFunctionContext): Record<string, string> {+ const hogFlow = (context.invocation as { hogFlow?: HogFlow }).hogFlow+ return hogFlow?.id ? { 'X-PostHog-Hog-Flow-Id': hogFlow.id } : {}+}+registerAsyncFunction('postHogGetAccount', {execute: async (args, context, result) => {const [opts] = args as [Record<string, any> | undefined]@@ -17,6 +63,13 @@ registerAsyncFunction('postHogGetAccount', {throw new Error("[HogFunction] - postHogGetAccount call missing 'external_id' property")}+ if (context.customerAnalyticsAccountsJwt.enabled) {+ // No team fetch and no secret_api_token requirement: teams that never minted the+ // legacy key can use account actions once the JWT secret is provisioned.+ await callInternalAccountApi(context, result, externalId, { method: 'GET' })+ return+ }+const team = await getTeamWithSecretToken(context, 'postHogGetAccount', ACCOUNT_ACTIONS)result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({@@ -77,6 +130,17 @@ registerAsyncFunction('postHogUpdateAccount', {throw new Error("[HogFunction] - postHogUpdateAccount call missing 'external_id' property")}+ if (context.customerAnalyticsAccountsJwt.enabled) {+ // external_id spreads last so no updates value can differ from the token's claim —+ // Django rejects a body whose external_id does not match the claim.+ await callInternalAccountApi(context, result, externalId, {+ method: 'PATCH',+ body: JSON.stringify({ ...updates, external_id: externalId }),+ extraHeaders: hogFlowHeaders(context),+ })+ return+ }+const team = await getTeamWithSecretToken(context, 'postHogUpdateAccount', ACCOUNT_ACTIONS)const headers: Record<string, string> = {@@ -84,10 +148,7 @@ registerAsyncFunction('postHogUpdateAccount', {Authorization: `Bearer ${team.secret_api_token}`,}- const hogFlow = (context.invocation as { hogFlow?: HogFlow }).hogFlow- if (hogFlow?.id) {- headers['X-PostHog-Hog-Flow-Id'] = hogFlow.id- }+ Object.assign(headers, hogFlowHeaders(context))result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({type: 'fetch',@@ -127,6 +188,16 @@ registerAsyncFunction('postHogSetAccountProperties', {throw new Error("[HogFunction] - postHogSetAccountProperties call missing 'external_id' property")}+ if (context.customerAnalyticsAccountsJwt.enabled) {+ await callInternalAccountApi(context, result, externalId, {+ method: 'PATCH',+ subpath: '/custom_property_values',+ body: JSON.stringify({ external_id: externalId, properties }),+ extraHeaders: hogFlowHeaders(context),+ })+ return+ }+const team = await getTeamWithSecretToken(context, 'postHogSetAccountProperties', ACCOUNT_ACTIONS)const headers: Record<string, string> = {@@ -134,10 +205,7 @@ registerAsyncFunction('postHogSetAccountProperties', {Authorization: `Bearer ${team.secret_api_token}`,}- const hogFlow = (context.invocation as { hogFlow?: HogFlow }).hogFlow- if (hogFlow?.id) {- headers['X-PostHog-Hog-Flow-Id'] = hogFlow.id- }+ Object.assign(headers, hogFlowHeaders(context))result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({type: 'fetch',@@ -176,6 +244,15 @@ registerAsyncFunction('postHogCreateAccount', {throw new Error("[HogFunction] - postHogCreateAccount call missing 'external_id' property")}+ if (context.customerAnalyticsAccountsJwt.enabled) {+ await callInternalAccountApi(context, result, externalId, {+ method: 'POST',+ body: JSON.stringify({ external_id: externalId }),+ extraHeaders: hogFlowHeaders(context),+ })+ return+ }+const team = await getTeamWithSecretToken(context, 'postHogCreateAccount', ACCOUNT_ACTIONS)const headers: Record<string, string> = {@@ -183,10 +260,7 @@ registerAsyncFunction('postHogCreateAccount', {Authorization: `Bearer ${team.secret_api_token}`,}- const hogFlow = (context.invocation as { hogFlow?: HogFlow }).hogFlow- if (hogFlow?.id) {- headers['X-PostHog-Hog-Flow-Id'] = hogFlow.id- }+ Object.assign(headers, hogFlowHeaders(context))result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({type: 'fetch',diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex cbc25a5ff830..cf5c32387573 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -158,6 +158,7 @@ export type CdpCoreServicesConfig = Pick<| 'EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD'| 'CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN'| 'CONVERSATIONS_TICKETS_JWT_SECRET'+ | 'CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET'| 'CDP_FETCH_RETRIES'| 'CDP_FETCH_BACKOFF_BASE_MS'| 'CDP_FETCH_BACKOFF_MAX_MS'@@ -472,6 +473,10 @@ export function createCdpCoreServices(PosthogJwtAudience.CONVERSATIONS_TICKETS,config.CONVERSATIONS_TICKETS_JWT_SECRET),+ customerAnalyticsAccountsJwt: new ScopedServiceJwt(+ PosthogJwtAudience.CUSTOMER_ANALYTICS_ACCOUNTS,+ config.CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET+ ),hogInputsService,emailService,recipientTokensService,diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex 0c7bb8588ced..a46f29a50fae 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -171,6 +171,7 @@ export type CdpConfig = ClickhouseConfig & {// (see .agents/security.md): empty in prod means the route fails closed until provisioned.WORKFLOWS_RESCHEDULE_JWT_SECRET: stringCONVERSATIONS_TICKETS_JWT_SECRET: string+ CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET: string// Scoped JWT keys verifying Django's calls to the cancel routes (invocations/cancel and// batch_jobs/:id/cancel). A dedicated key, separate from the reschedule sweep's above: the// web tier mints cancels while the worker mints reschedules, so neither tier's key can forge@@ -349,6 +350,10 @@ export function getDefaultCdpConfig(): CdpConfig {// Dev default must equal Django's CONVERSATIONS_TICKETS_JWT_SECRETS default so local// end-to-end works; empty in prod until provisioned (worker then stays on legacy auth).CONVERSATIONS_TICKETS_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-conversations-tickets-jwt' : '',+ // Dev default must equal Django's CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRETS default so local+ // end-to-end works; empty in prod until provisioned (worker then stays on legacy auth).+ CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET:+ isTestEnv() || isDevEnv() ? 'local-dev-customer-analytics-accounts-jwt' : '',// Dev/test default must match Django's (posthog/settings/data_stores.py).WORKFLOWS_CANCEL_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-workflows-cancel-jwt' : '',// Dev/test default must match Django's (posthog/settings/data_stores.py).diff --git a/nodejs/src/cdp/services/hog-executor-async.service.ts b/nodejs/src/cdp/services/hog-executor-async.service.tsindex a7231afb8585..25b8da07bde3 100644--- a/nodejs/src/cdp/services/hog-executor-async.service.ts+++ b/nodejs/src/cdp/services/hog-executor-async.service.ts@@ -60,6 +60,7 @@ export interface HogExecutorAsyncConfig {export interface HogExecutorAsyncDependencies {teamManager: TeamManagerconversationsTicketsJwt: ScopedServiceJwt+ customerAnalyticsAccountsJwt: ScopedServiceJwthogInputsService: HogInputsServiceemailService: EmailServicerecipientTokensService: RecipientTokensService@@ -269,6 +270,7 @@ export class HogExecutorAsyncService {siteUrl: this.config.siteUrl,internalApiBaseUrl: this.config.internalApiBaseUrl,conversationsTicketsJwt: this.deps.conversationsTicketsJwt,+ customerAnalyticsAccountsJwt: this.deps.customerAnalyticsAccountsJwt,consumeInlineAsyncBudget,},resultdiff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.tsindex dd22b7a7599f..a18e1d2c9c02 100644--- a/nodejs/src/cdp/services/hog-executor.service.test.ts+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts@@ -102,6 +102,10 @@ describe('Hog Executor', () => {PosthogJwtAudience.CONVERSATIONS_TICKETS,hub.CONVERSATIONS_TICKETS_JWT_SECRET),+ customerAnalyticsAccountsJwt: new ScopedServiceJwt(+ PosthogJwtAudience.CUSTOMER_ANALYTICS_ACCOUNTS,+ hub.CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET+ ),hogInputsService,emailService,recipientTokensService,@@ -956,7 +960,7 @@ describe('Hog Executor', () => {})})- describe('postHogGetAccount', () => {+ describe('account workflow actions', () => {const mockExecHogForAsyncFunction = (asyncFunctionName: string, asyncFunctionArgs: any[]) => {const hogExecModule = require('../utils/hog-exec')jest.spyOn(hogExecModule, 'execHog').mockResolvedValue({@@ -981,129 +985,248 @@ describe('Hog Executor', () => {{ inputs: {} })- it('postHogGetAccount queues internal fetch with the external_id query param', async () => {- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({- id: 1,- secret_api_token: 'test-secret-token',- } as any)+ const requestModule = require('~/common/utils/request')- mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme corp/1' }])+ const mockInternalResponse = (status: number, body: unknown) => ({+ status,+ headers: {},+ text: () => Promise.resolve(JSON.stringify(body)),+ json: () => Promise.resolve(body),+ dump: () => Promise.resolve(),+ })- const result = await executor.execute(createAccountInvocation())+ const verifyAccountClaims = (headers: Record<string, string>) =>+ new ScopedServiceJwt(+ PosthogJwtAudience.CUSTOMER_ANALYTICS_ACCOUNTS,+ hub.CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET+ ).verify(headers['Authorization'].replace('Bearer ', ''))- expect(result.invocation.queueParameters).toEqual({- type: 'fetch',- url: `${hub.SITE_URL}/api/customer_analytics/external/account?external_id=acme%20corp%2F1`,- method: 'GET',- headers: { Authorization: 'Bearer test-secret-token' },+ // In the test env the secret defaults on (mirroring Django), so the JWT path is the+ // default; legacy tests opt out the same way an unprovisioned environment does.+ const disableAccountJwt = () => {+ ;(executor as any).deps.customerAnalyticsAccountsJwt = new ScopedServiceJwt(+ PosthogJwtAudience.CUSTOMER_ANALYTICS_ACCOUNTS,+ ''+ )+ }++ describe('scoped JWT path', () => {+ // Transport behavior (retries, 4xx pass-through, async budget) is shared with the+ // ticket actions and covered by their suite; these pin the account-specific wiring.++ it('postHogGetAccount mints a team+account pinned token for the internal route and needs no team secret', async () => {+ const fetchSpy = jest+ .spyOn(requestModule, 'internalFetch')+ .mockResolvedValue(mockInternalResponse(200, { external_id: 'acme corp/1', name: 'Acme' }))+ const getTeamSpy = jest.spyOn(hub.teamManager, 'getTeam')++ mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme corp/1' }])+ const result = await executor.execute(createAccountInvocation())++ expect(fetchSpy).toHaveBeenCalledTimes(1)+ const [url, options] = fetchSpy.mock.calls[0] as unknown as [string, FetchOptions]+ // URL-encoded in the query string; the claim carries the raw value Django reads+ // back from the decoded query param.+ expect(url).toEqual(+ `${hub.INTERNAL_API_BASE_URL}/api/projects/1/internal/customer_analytics/account?external_id=acme%20corp%2F1`+ )+ expect(options.method).toEqual('GET')++ const claims = verifyAccountClaims(options.headers as Record<string, string>)+ expect(claims.team_id).toEqual(1)+ expect(claims.external_id).toEqual('acme corp/1')+ expect(claims.exp! - claims.iat!).toEqual(5 * 60)++ expect(result.invocation.state.vmState!.stack).toEqual([+ { status: 200, body: { external_id: 'acme corp/1', name: 'Acme' } },+ ])+ // No credential is needed or persisted: the team secret is never read and+ // nothing lands in queueParameters (job rows stay free of auth material).+ expect(getTeamSpy).not.toHaveBeenCalled()+ expect(result.invocation.queueParameters).toBeUndefined()})- })- it('postHogGetAccount errors when external_id is missing', async () => {- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({- id: 1,- secret_api_token: 'test-secret-token',- } as any)+ it('postHogUpdateAccount pins the claimed external_id over the updates body', async () => {+ const fetchSpy = jest+ .spyOn(requestModule, 'internalFetch')+ .mockResolvedValue(mockInternalResponse(200, { ok: true }))- mockExecHogForAsyncFunction('postHogGetAccount', [{}])+ mockExecHogForAsyncFunction('postHogUpdateAccount', [+ // A Hog-provided updates.external_id must not redirect the write away from+ // the account the token is pinned to.+ { external_id: 'acme-1', updates: { tags: ['enterprise'], external_id: 'other-account' } },+ ])+ const invocation = createAccountInvocation()+ ;(invocation as any).hogFlow = { id: 'flow-123' }+ await executor.execute(invocation)- const result = await executor.execute(createAccountInvocation())- expect(result.error).toContain("missing 'external_id'")- })+ const [url, options] = fetchSpy.mock.calls[0] as unknown as [string, FetchOptions]+ expect(url).toEqual(`${hub.INTERNAL_API_BASE_URL}/api/projects/1/internal/customer_analytics/account`)+ expect(options.method).toEqual('PATCH')+ expect(options.body).toEqual(JSON.stringify({ tags: ['enterprise'], external_id: 'acme-1' }))+ expect((options.headers as Record<string, string>)['X-PostHog-Hog-Flow-Id']).toEqual('flow-123')+ const claims = verifyAccountClaims(options.headers as Record<string, string>)+ expect(claims.external_id).toEqual('acme-1')+ })- it('postHogGetAccount errors when team is not found', async () => {- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue(null)+ it('postHogSetAccountProperties targets the custom_property_values route', async () => {+ const fetchSpy = jest+ .spyOn(requestModule, 'internalFetch')+ .mockResolvedValue(mockInternalResponse(200, { ok: true }))- mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme-1' }])+ mockExecHogForAsyncFunction('postHogSetAccountProperties', [+ { external_id: 'acme-1', properties: { 'def-1': 'gold' } },+ ])+ await executor.execute(createAccountInvocation())- const result = await executor.execute(createAccountInvocation())- expect(result.error).toContain('Team 1 not found')- })+ const [url, options] = fetchSpy.mock.calls[0] as unknown as [string, FetchOptions]+ expect(url).toEqual(+ `${hub.INTERNAL_API_BASE_URL}/api/projects/1/internal/customer_analytics/account/custom_property_values`+ )+ expect(options.method).toEqual('PATCH')+ expect(options.body).toEqual(JSON.stringify({ external_id: 'acme-1', properties: { 'def-1': 'gold' } }))+ })- it('postHogGetAccount errors when the team has no secret API token', async () => {- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({- id: 1,- secret_api_token: null,- } as any)+ it('postHogCreateAccount posts the claimed external_id with workflow attribution', async () => {+ const fetchSpy = jest+ .spyOn(requestModule, 'internalFetch')+ .mockResolvedValue(mockInternalResponse(201, { external_id: 'acme-new' }))- mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme-1' }])+ mockExecHogForAsyncFunction('postHogCreateAccount', [{ external_id: 'acme-new' }])+ const invocation = createAccountInvocation()+ ;(invocation as any).hogFlow = { id: 'flow-123' }+ const result = await executor.execute(invocation)- const result = await executor.execute(createAccountInvocation())- // The message reaches the customer verbatim in the workflow logs, so it has to name- // the setup step rather than the field.- expect(result.error).toContain('This project has no secret API key')- expect(result.error).toContain('account workflow actions')- expect(result.error).toContain('Settings > Support > Secret API key')+ const [url, options] = fetchSpy.mock.calls[0] as unknown as [string, FetchOptions]+ expect(url).toEqual(`${hub.INTERNAL_API_BASE_URL}/api/projects/1/internal/customer_analytics/account`)+ expect(options.method).toEqual('POST')+ expect(options.body).toEqual(JSON.stringify({ external_id: 'acme-new' }))+ expect((options.headers as Record<string, string>)['X-PostHog-Hog-Flow-Id']).toEqual('flow-123')+ const claims = verifyAccountClaims(options.headers as Record<string, string>)+ expect(claims.external_id).toEqual('acme-new')+ expect(result.invocation.state.vmState!.stack).toEqual([+ { status: 201, body: { external_id: 'acme-new' } },+ ])+ })})- it('captures exception with team_id when secret API token is missing', async () => {- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({- id: 1,- secret_api_token: null,- } as any)+ describe('legacy secret_api_token fallback (JWT secret unprovisioned)', () => {+ it('postHogGetAccount queues external fetch with the external_id query param', async () => {+ disableAccountJwt()+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({+ id: 1,+ secret_api_token: 'test-secret-token',+ } as any)- const posthogModule = require('~/common/utils/posthog')- const captureExceptionSpy = jest.spyOn(posthogModule, 'captureException')+ mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme corp/1' }])- mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme-1' }])- await executor.execute(createAccountInvocation())+ const result = await executor.execute(createAccountInvocation())- expect(captureExceptionSpy).toHaveBeenCalledWith(- expect.any(Error),- expect.objectContaining({ tags: expect.objectContaining({ team_id: 1 }) })- )- })+ expect(result.invocation.queueParameters).toEqual({+ type: 'fetch',+ url: `${hub.SITE_URL}/api/customer_analytics/external/account?external_id=acme%20corp%2F1`,+ method: 'GET',+ headers: { Authorization: 'Bearer test-secret-token' },+ })+ })- it('does not capture exception when queue is set up successfully', async () => {- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({- id: 1,- secret_api_token: 'test-secret-token',- } as any)+ it('postHogGetAccount errors when team is not found', async () => {+ disableAccountJwt()+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue(null)- const posthogModule = require('~/common/utils/posthog')- const captureExceptionSpy = jest.spyOn(posthogModule, 'captureException')+ mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme-1' }])- mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme-1' }])- await executor.execute(createAccountInvocation())+ const result = await executor.execute(createAccountInvocation())+ expect(result.error).toContain('Team 1 not found')+ })- expect(captureExceptionSpy).not.toHaveBeenCalled()- })+ it('postHogGetAccount errors when the team has no secret API token', async () => {+ disableAccountJwt()+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({+ id: 1,+ secret_api_token: null,+ } as any)- it('postHogUpdateAccount queues a PATCH with external_id merged into the body', async () => {- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({- id: 1,- secret_api_token: 'test-secret-token',- } as any)+ mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme-1' }])- mockExecHogForAsyncFunction('postHogUpdateAccount', [- { external_id: 'acme-1', updates: { tags: ['enterprise'], tags_mode: 'add' } },- ])+ const result = await executor.execute(createAccountInvocation())+ // The message reaches the customer verbatim in the workflow logs, so it has to name+ // the setup step rather than the field.+ expect(result.error).toContain('This project has no secret API key')+ expect(result.error).toContain('account workflow actions')+ expect(result.error).toContain('Settings > Support > Secret API key')+ })++ it('captures exception with team_id when secret API token is missing', async () => {+ disableAccountJwt()+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({+ id: 1,+ secret_api_token: null,+ } as any)- const result = await executor.execute(createAccountInvocation())+ const posthogModule = require('~/common/utils/posthog')+ const captureExceptionSpy = jest.spyOn(posthogModule, 'captureException')- expect(result.invocation.queueParameters).toEqual({- type: 'fetch',- url: `${hub.SITE_URL}/api/customer_analytics/external/account`,- method: 'PATCH',- body: JSON.stringify({ external_id: 'acme-1', tags: ['enterprise'], tags_mode: 'add' }),- headers: {- 'Content-Type': 'application/json',- Authorization: 'Bearer test-secret-token',- },+ mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme-1' }])+ await executor.execute(createAccountInvocation())++ expect(captureExceptionSpy).toHaveBeenCalledWith(+ expect.any(Error),+ expect.objectContaining({ tags: expect.objectContaining({ team_id: 1 }) })+ )})- })- it('postHogUpdateAccount errors when external_id is missing', async () => {- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({- id: 1,- secret_api_token: 'test-secret-token',- } as any)+ it('does not capture exception when queue is set up successfully', async () => {+ disableAccountJwt()+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({+ id: 1,+ secret_api_token: 'test-secret-token',+ } as any)++ const posthogModule = require('~/common/utils/posthog')+ const captureExceptionSpy = jest.spyOn(posthogModule, 'captureException')++ mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme-1' }])+ await executor.execute(createAccountInvocation())++ expect(captureExceptionSpy).not.toHaveBeenCalled()+ })++ it('postHogUpdateAccount queues a PATCH with external_id merged into the body', async () => {+ disableAccountJwt()+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({+ id: 1,+ secret_api_token: 'test-secret-token',+ } as any)++ mockExecHogForAsyncFunction('postHogUpdateAccount', [+ { external_id: 'acme-1', updates: { tags: ['enterprise'], tags_mode: 'add' } },+ ])- mockExecHogForAsyncFunction('postHogUpdateAccount', [{ updates: { tags: ['enterprise'] } }])+ const result = await executor.execute(createAccountInvocation())- const result = await executor.execute(createAccountInvocation())- expect(result.error).toContain("missing 'external_id'")+ expect(result.invocation.queueParameters).toEqual({+ type: 'fetch',+ url: `${hub.SITE_URL}/api/customer_analytics/external/account`,+ method: 'PATCH',+ body: JSON.stringify({ external_id: 'acme-1', tags: ['enterprise'], tags_mode: 'add' }),+ headers: {+ 'Content-Type': 'application/json',+ Authorization: 'Bearer test-secret-token',+ },+ })+ })})++ it.each(['postHogGetAccount', 'postHogUpdateAccount', 'postHogSetAccountProperties', 'postHogCreateAccount'])(+ '%s errors when external_id is missing',+ async (name) => {+ mockExecHogForAsyncFunction(name, [{}])++ const result = await executor.execute(createAccountInvocation())+ expect(result.error).toContain("missing 'external_id'")+ }+ )})describe('produceToWarehouseWebhooks', () => {diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.tsindex 56e60d11bbf1..657c82304664 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts@@ -89,6 +89,10 @@ describe('HogFunctionHandler', () => {PosthogJwtAudience.CONVERSATIONS_TICKETS,hub.CONVERSATIONS_TICKETS_JWT_SECRET),+ customerAnalyticsAccountsJwt: new ScopedServiceJwt(+ PosthogJwtAudience.CUSTOMER_ANALYTICS_ACCOUNTS,+ hub.CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET+ ),hogInputsService,emailService,recipientTokensService,diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.tsindex fda3d406e711..90eecdbf890f 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts@@ -111,6 +111,10 @@ describe('Hogflow Executor', () => {PosthogJwtAudience.CONVERSATIONS_TICKETS,hub.CONVERSATIONS_TICKETS_JWT_SECRET),+ customerAnalyticsAccountsJwt: new ScopedServiceJwt(+ PosthogJwtAudience.CUSTOMER_ANALYTICS_ACCOUNTS,+ hub.CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET+ ),hogInputsService,emailService,recipientTokensService,diff --git a/nodejs/src/cdp/templates/test/test-helpers.ts b/nodejs/src/cdp/templates/test/test-helpers.tsindex c746c9ddce39..7f1b8a810814 100644--- a/nodejs/src/cdp/templates/test/test-helpers.ts+++ b/nodejs/src/cdp/templates/test/test-helpers.ts@@ -235,6 +235,7 @@ export class TemplateTester {// invokeFetchResponse simulates any transport's response push. The scoped-JWT// transport itself is covered in hog-executor.service.test.ts.conversationsTicketsJwt: new ScopedServiceJwt(PosthogJwtAudience.CONVERSATIONS_TICKETS, ''),+ customerAnalyticsAccountsJwt: new ScopedServiceJwt(PosthogJwtAudience.CUSTOMER_ANALYTICS_ACCOUNTS, ''),hogInputsService,emailService,recipientTokensService,diff --git a/nodejs/src/cdp/utils/jwt-utils.ts b/nodejs/src/cdp/utils/jwt-utils.tsindex 1c33c5386e60..f0bf43db5313 100644--- a/nodejs/src/cdp/utils/jwt-utils.ts+++ b/nodejs/src/cdp/utils/jwt-utils.ts@@ -9,6 +9,8 @@ export enum PosthogJwtAudience {TASKS_CREATE = 'posthog:tasks:create',// Must match PosthogJwtAudience.CONVERSATIONS_TICKETS in posthog/jwt.py exactly.CONVERSATIONS_TICKETS = 'posthog:conversations:tickets',+ // Must match PosthogJwtAudience.CUSTOMER_ANALYTICS_ACCOUNTS in posthog/jwt.py exactly.+ CUSTOMER_ANALYTICS_ACCOUNTS = 'posthog:customer_analytics:accounts',}export class JWT {