: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): remove legacy secret_api_token worker path (#103176)
Patricioaadbf68d861c
diff --git a/.agents/security.md b/.agents/security.mdindex 692e80cb45a9..56b9cd6232cd 100644--- a/.agents/security.md+++ b/.agents/security.md@@ -22,7 +22,7 @@ Default to the smallest permission, narrowest field set, and shortest scope that- **Don't extend `SECRET_KEY` to new purposes.** Do not add code that reads `settings.SECRET_KEY` (or derives keys from it) for a new job. Mint a dedicated setting in `posthog/settings/` read from its own env var — e.g. `<PURPOSE>_SIGNING_KEY` / `<PURPOSE>_SECRET_KEYS`. A genuinely new purpose must NOT fall back to `SECRET_KEY`; fail closed when unprovisioned instead. Canonical example: `RECORDING_API_JWT_SECRET` (`posthog/settings/session_replay_v2.py`) — no `SECRET_KEY` default, empty in prod so only designated minters can sign. (Older keys like `JWT_SIGNING_KEY`, `TEMPORAL_SECRET_KEY`, `FLAGS_SECRET_KEYS` default to `SECRET_KEY` for self-hosted back-compat; that is migration debt, not the pattern to copy for new keys.)- **Support rotation from day one.** Read the key as a list, newest first: the first element signs/encrypts, all elements are tried for verify/decrypt. Prefer a single comma-separated env var (`KEY="<new>,<old>"`) parsed with `get_list()` — the Fernet `new,old` convention. Examples: `RECORDING_API_JWT_SECRET` (`recording_api_jwt.py`), `FLAGS_SECRET_KEYS` (`encrypted_flag_payloads.py`). For encryption use `MultiFernet` (encrypt with first, decrypt with any) — see `posthog/helpers/encrypted_fields.py`. Encrypting data at rest? ship a re-encryption path that re-wraps onto the primary key, like `posthog/management/commands/reencrypt_fields.py`. The primary + `_FALLBACKS` pair (`JWT_SIGNING_KEY` / `JWT_SIGNING_KEY_FALLBACKS`) is the older two-var variant; single-var comma-separated is preferred for new keys.- **Unique value per environment — including prod US and prod EU.** Never share a key value across environments; provision each (dev, prod-US, prod-EU) independently so one region can rotate without breaking another and a leak in one doesn't compromise the rest. Enforced at provisioning, not in code — so never hardcode a shared prod default. Fail closed when a prod key is unset (mirror the `SECRET_KEY` startup guard in `posthog/settings/access.py` and `RECORDING_API_JWT_SECRET`'s empty-in-prod default).-- **Don't extend `INTERNAL_API_SECRET` to new service-to-service calls.** It's a single fleet-wide shared secret already trusted by many services across Django, Node, and Rust — one leak reaches all of them — so it must not grow new callers or protected endpoints (it's being actively retired edge-by-edge; adding one moves it backwards). For a new internal call, in order of preference: (1) **mint a scoped JWT (strongly preferred)** — a dedicated per-audience signing key (never `INTERNAL_API_SECRET`/`SECRET_KEY`/`JWT_SIGNING_KEY`) with claims pinning the token to its team and operation, verified per-route; canonical example `RECORDING_API_JWT_SECRET` (mint in `posthog/session_recordings/recordings/recording_api_jwt.py`, verify in `nodejs/src/session-replay/recording-api/auth.ts`). (2) If a JWT genuinely doesn't fit, **a dedicated static secret** scoped to that one caller→callee pair (`<PURPOSE>_API_SECRET`, its own env var, rotatable, empty-in-prod-fail-closed) — never reuse `INTERNAL_API_SECRET`. The goal is blast radius: no single "master" credential that authenticates to a dozen services — a scoped JWT limits a leak to one team + operation; a dedicated secret limits it to one hop.+- **Don't extend `INTERNAL_API_SECRET` to new service-to-service calls.** It's a single fleet-wide shared secret already trusted by many services across Django, Node, and Rust — one leak reaches all of them — so it must not grow new callers or protected endpoints (it's being actively retired edge-by-edge; adding one moves it backwards). For a new internal call, in order of preference: (1) **mint a scoped JWT (strongly preferred)** — a dedicated per-audience signing key (never `INTERNAL_API_SECRET`/`SECRET_KEY`/`JWT_SIGNING_KEY`) with claims pinning the token to its team and operation, verified per-route; use the shared machinery instead of hand-rolling: `ScopedServiceJwtPurpose` + `ScopedServiceJWTAuthentication` in `posthog/scoped_service_jwt.py` (Django mint/verify) and `ScopedServiceJwt` in `nodejs/src/cdp/utils/scoped-service-jwt.ts` (Node mint/verify); worked examples: the conversations ticket route (`products/conversations/backend/api/internal.py`) and its minting worker (`nodejs/src/cdp/async-functions/internal-api-call.ts`). (2) If a JWT genuinely doesn't fit, **a dedicated static secret** scoped to that one caller→callee pair (`<PURPOSE>_API_SECRET`, its own env var, rotatable, empty-in-prod-fail-closed) — never reuse `INTERNAL_API_SECRET`. The goal is blast radius: no single "master" credential that authenticates to a dozen services — a scoped JWT limits a leak to one team + operation; a dedicated secret limits it to one hop.## SQL Securitydiff --git a/nodejs/src/cdp/async-functions/conversations.ts b/nodejs/src/cdp/async-functions/conversations.tsindex cbae0b07f77a..e1c7b37d71c9 100644--- a/nodejs/src/cdp/async-functions/conversations.ts+++ b/nodejs/src/cdp/async-functions/conversations.ts@@ -1,21 +1,18 @@import { DateTime } from 'luxon'-import { CyclotronInvocationQueueParametersFetchSchema } from '~/cdp/schema/cyclotron'import { HogFlow } from '~/cdp/schema/hogflow'import { AsyncFunctionContext } from '../async-function-registry'import { registerAsyncFunction } from '../async-function-registry'import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult } from '../types'import { UUID_RE, callInternalApi } from './internal-api-call'-import { getTeamWithSecretToken } from './secret-api-token'const TICKET_ACTIONS = 'ticket workflow actions'/*** Calls the JWT-only internal ticket route (products/conversations/backend/api/internal.py).* The token pins the invocation's own team plus this one ticket; Django refuses it anywhere- * else. Used whenever CONVERSATIONS_TICKETS_JWT_SECRET is provisioned — the legacy- * secret_api_token path below it is the fallback until then (#82564).+ * else (#82564).*/async function callInternalTicketApi(context: AsyncFunctionContext,@@ -23,6 +20,14 @@ async function callInternalTicketApi(ticketId: string,options: { method: 'GET' | 'PATCH'; query?: string; body?: string; extraHeaders?: Record<string, string> }): Promise<void> {+ // Reaches the operator verbatim in the workflow logs. Keep it free of square brackets,+ // which the log viewer parses as entity chips and would swallow.+ if (!context.conversationsTicketsJwt.enabled) {+ throw new Error(+ `This PostHog deployment has no CONVERSATIONS_TICKETS_JWT_SECRET configured, so ${TICKET_ACTIONS} ` ++ `can't authenticate. Set the same value for the web service and the CDP worker.`+ )+ }// The ticket id becomes a URL segment and a token claim, so only a UUID may pass — Hog// code controls this value. Lowercased because Django's <uuid:> converter and the claim// comparison only accept the canonical form.@@ -53,21 +58,7 @@ registerAsyncFunction('postHogGetTicket', {const query =opts?.include_first_customer_message_text === true ? '?include_first_customer_message_text=true' : ''- if (context.conversationsTicketsJwt.enabled) {- // No team fetch and no secret_api_token requirement: teams that never minted the- // legacy key can use ticket actions once the JWT secret is provisioned.- await callInternalTicketApi(context, result, ticketId, { method: 'GET', query })- return- }-- const team = await getTeamWithSecretToken(context, 'postHogGetTicket', TICKET_ACTIONS)-- result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({- type: 'fetch',- url: `${context.siteUrl}/api/conversations/external/ticket/${ticketId}${query}`,- method: 'GET',- headers: { Authorization: `Bearer ${team.secret_api_token}` },- })+ await callInternalTicketApi(context, result, ticketId, { method: 'GET', query })},mock: (args, logs) => {@@ -137,27 +128,10 @@ registerAsyncFunction('postHogUpdateTicket', {const hogFlow = (context.invocation as { hogFlow?: HogFlow }).hogFlowconst hogFlowHeaders: Record<string, string> = hogFlow?.id ? { 'X-PostHog-Hog-Flow-Id': hogFlow.id } : {}- if (context.conversationsTicketsJwt.enabled) {- await callInternalTicketApi(context, result, ticketId, {- method: 'PATCH',- body: JSON.stringify(updates),- extraHeaders: hogFlowHeaders,- })- return- }-- const updateTeam = await getTeamWithSecretToken(context, 'postHogUpdateTicket', TICKET_ACTIONS)-- result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({- type: 'fetch',- url: `${context.siteUrl}/api/conversations/external/ticket/${ticketId}`,+ await callInternalTicketApi(context, result, ticketId, {method: 'PATCH',body: JSON.stringify(updates),- headers: {- 'Content-Type': 'application/json',- Authorization: `Bearer ${updateTeam.secret_api_token}`,- ...hogFlowHeaders,- },+ extraHeaders: hogFlowHeaders,})},diff --git a/nodejs/src/cdp/async-functions/customer_analytics.ts b/nodejs/src/cdp/async-functions/customer_analytics.tsindex 943094f83e36..58c4ebb5964c 100644--- a/nodejs/src/cdp/async-functions/customer_analytics.ts+++ b/nodejs/src/cdp/async-functions/customer_analytics.ts@@ -1,12 +1,10 @@import { DateTime } from 'luxon'-import { CyclotronInvocationQueueParametersFetchSchema } from '~/cdp/schema/cyclotron'import { HogFlow } from '~/cdp/schema/hogflow'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'const CLEAR_PROPERTY_MARKER = '__posthog_clear_property'@@ -39,9 +37,7 @@ function normalizeAccountProperties(properties: Record<string, unknown>): Record/*** 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).+ * account's external_id; Django refuses it anywhere else (#82564).*/async function callInternalAccountApi(context: AsyncFunctionContext,@@ -54,6 +50,14 @@ async function callInternalAccountApi(extraHeaders?: Record<string, string>}): Promise<void> {+ // Reaches the operator verbatim in the workflow logs. Keep it free of square brackets,+ // which the log viewer parses as entity chips and would swallow.+ if (!context.customerAnalyticsAccountsJwt.enabled) {+ throw new Error(+ `This PostHog deployment has no CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET configured, so ` ++ `${ACCOUNT_ACTIONS} can't authenticate. Set the same value for the web service and the CDP worker.`+ )+ }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@@ -89,21 +93,7 @@ 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({- type: 'fetch',- url: `${context.siteUrl}/api/customer_analytics/external/account?external_id=${encodeURIComponent(externalId)}`,- method: 'GET',- headers: { Authorization: `Bearer ${team.secret_api_token}` },- })+ await callInternalAccountApi(context, result, externalId, { method: 'GET' })},mock: (args, logs) => {@@ -156,32 +146,12 @@ 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> = {- 'Content-Type': 'application/json',- Authorization: `Bearer ${team.secret_api_token}`,- }-- Object.assign(headers, hogFlowHeaders(context))-- result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({- type: 'fetch',- url: `${context.siteUrl}/api/customer_analytics/external/account`,+ // 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({ external_id: externalId, ...updates }),- headers,+ body: JSON.stringify({ ...updates, external_id: externalId }),+ extraHeaders: hogFlowHeaders(context),})},@@ -216,31 +186,11 @@ registerAsyncFunction('postHogSetAccountProperties', {const normalizedProperties = normalizeAccountProperties(properties)- if (context.customerAnalyticsAccountsJwt.enabled) {- await callInternalAccountApi(context, result, externalId, {- method: 'PATCH',- subpath: '/custom_property_values',- body: JSON.stringify({ external_id: externalId, properties: normalizedProperties }),- extraHeaders: hogFlowHeaders(context),- })- return- }-- const team = await getTeamWithSecretToken(context, 'postHogSetAccountProperties', ACCOUNT_ACTIONS)-- const headers: Record<string, string> = {- 'Content-Type': 'application/json',- Authorization: `Bearer ${team.secret_api_token}`,- }-- Object.assign(headers, hogFlowHeaders(context))-- result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({- type: 'fetch',- url: `${context.siteUrl}/api/customer_analytics/external/account/custom_property_values`,+ await callInternalAccountApi(context, result, externalId, {method: 'PATCH',+ subpath: '/custom_property_values',body: JSON.stringify({ external_id: externalId, properties: normalizedProperties }),- headers,+ extraHeaders: hogFlowHeaders(context),})},@@ -272,30 +222,10 @@ 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> = {- 'Content-Type': 'application/json',- Authorization: `Bearer ${team.secret_api_token}`,- }-- Object.assign(headers, hogFlowHeaders(context))-- result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({- type: 'fetch',- url: `${context.siteUrl}/api/customer_analytics/external/account`,+ await callInternalAccountApi(context, result, externalId, {method: 'POST',body: JSON.stringify({ external_id: externalId }),- headers,+ extraHeaders: hogFlowHeaders(context),})},diff --git a/nodejs/src/cdp/async-functions/secret-api-token.ts b/nodejs/src/cdp/async-functions/secret-api-token.tsdeleted file mode 100644index d8cc034ef25d..000000000000--- a/nodejs/src/cdp/async-functions/secret-api-token.ts+++ /dev/null@@ -1,45 +0,0 @@-import { captureException } from '~/common/utils/posthog'-import { Team } from '~/types'--import { AsyncFunctionContext } from '../async-function-registry'--/**- * Loads the team for a workflow action that calls back into PostHog's own API (tickets,- * accounts), which authenticates with the project's secret API token.- *- * Nothing provisions that token: enabling Support mints only the public widget token, so a- * project can be using tickets for months and still not have one. The message therefore names- * the setup step rather than the field - it reaches the customer verbatim in the workflow's- * logs, wrapped as "Workflow encountered an error: <message> at <action>". Keep it free of- * square brackets, which the log viewer parses as entity chips and would swallow.- *- * `actionDescription` completes "so ... can't authenticate", e.g. 'ticket workflow actions'.- */-export async function getTeamWithSecretToken(- context: AsyncFunctionContext,- functionName: string,- actionDescription: string-): Promise<Team> {- const team = await context.teamManager.getTeam(context.invocation.teamId)- if (!team) {- throw new Error(`Team ${context.invocation.teamId} not found`)- }- if (!team.secret_api_token) {- // Naming the admin requirement matters: rotate_secret_token is gated by- // TeamMemberStrictManagementPermission, so a regular member following the- // instructions would otherwise reach a disabled button.- const error = new Error(- `This project has no secret API key, so ${actionDescription} can't authenticate. ` +- `A project admin can generate one in Settings > Support > Secret API key.`- )- captureException(error, {- tags: {- team_id: context.invocation.teamId,- function: functionName,- template_id: context.invocation.hogFunction.template_id ?? null,- },- })- throw error- }- return team-}diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.tsindex ac07708f68a9..624f785334ad 100644--- a/nodejs/src/cdp/services/hog-executor.service.test.ts+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts@@ -853,104 +853,18 @@ describe('Hog Executor', () => {})})- describe('legacy secret_api_token fallback (JWT secret unprovisioned)', () => {- it('postHogGetTicket queues the external fetch with the team secret', async () => {+ describe('unprovisioned JWT secret', () => {+ it('fails the action with instructions naming the env var', async () => {disableTicketJwt()- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({- id: 1,- secret_api_token: 'test-secret-token',- } as any)-- mockExecHogForAsyncFunction('postHogGetTicket', [{ ticket_id: 'test-ticket-123' }])-- const result = await executor.execute(createTicketInvocation())-- expect(result.invocation.queueParameters).toEqual({- type: 'fetch',- url: `${hub.SITE_URL}/api/conversations/external/ticket/test-ticket-123`,- method: 'GET',- headers: { Authorization: 'Bearer test-secret-token' },- })- })-- it('postHogUpdateTicket queues the external fetch with the team secret', async () => {- disableTicketJwt()- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({- id: 1,- secret_api_token: 'test-secret-token',- } as any)-- mockExecHogForAsyncFunction('postHogUpdateTicket', [- { ticket_id: 'test-ticket-456', updates: { status: 'resolved', priority: 'high' } },- ])-- const result = await executor.execute(createTicketInvocation())-- expect(result.invocation.queueParameters).toEqual({- type: 'fetch',- url: `${hub.SITE_URL}/api/conversations/external/ticket/test-ticket-456`,- method: 'PATCH',- body: JSON.stringify({ status: 'resolved', priority: 'high' }),- headers: {- 'Content-Type': 'application/json',- Authorization: 'Bearer test-secret-token',- },- })- })-- it('postHogGetTicket errors when team is not found', async () => {- disableTicketJwt()- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue(null)-- mockExecHogForAsyncFunction('postHogGetTicket', [{ ticket_id: 'test-ticket-123' }])+ const fetchSpy = jest.spyOn(requestModule, 'internalFetch')+ mockExecHogForAsyncFunction('postHogGetTicket', [{ ticket_id: TICKET_UUID }])const result = await executor.execute(createTicketInvocation())- expect(result.error).toContain('Team 1 not found')- })-- it.each([- ['postHogGetTicket', { ticket_id: 'test-ticket-123' }],- ['postHogUpdateTicket', { ticket_id: 'test-ticket-456', updates: { status: 'new' } }],- ])('%s points at the setup step when the team has no secret API token', async (name, args) => {- disableTicketJwt()- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({- id: 1,- secret_api_token: null,- } as any)-- mockExecHogForAsyncFunction(name, [args])- const result = await executor.execute(createTicketInvocation())- // Nothing provisions this token, so the message has to name the setup step rather- // than the field - it reaches the customer verbatim in the workflow logs. Square- // brackets would be parsed as entity chips by the log viewer and swallowed.- expect(result.error).toContain('This project has no secret API key')+ expect(result.error).toContain('CONVERSATIONS_TICKETS_JWT_SECRET')expect(result.error).toContain('ticket workflow actions')- expect(result.error).toContain('Settings > Support > Secret API key')expect(result.error).not.toContain('[')- })-- it('captures exception with team_id when the ticket secret API token is missing', async () => {- disableTicketJwt()- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({- id: 1,- secret_api_token: null,- } as any)-- const posthogModule = require('~/common/utils/posthog')- const captureExceptionSpy = jest.spyOn(posthogModule, 'captureException')-- mockExecHogForAsyncFunction('postHogUpdateTicket', [- { ticket_id: 'test-ticket-456', updates: { status: 'new' } },- ])- await executor.execute(createTicketInvocation())-- expect(captureExceptionSpy).toHaveBeenCalledWith(- expect.any(Error),- expect.objectContaining({- tags: expect.objectContaining({ team_id: 1, function: 'postHogUpdateTicket' }),- })- )+ expect(fetchSpy).not.toHaveBeenCalled()})})@@ -1112,126 +1026,18 @@ describe('Hog Executor', () => {})})- 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)-- mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme corp/1' }])-- const result = await executor.execute(createAccountInvocation())-- 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('postHogGetAccount errors when team is not found', async () => {+ describe('unprovisioned JWT secret', () => {+ it('fails the action with instructions naming the env var', async () => {disableAccountJwt()- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue(null)+ const fetchSpy = jest.spyOn(requestModule, 'internalFetch')mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme-1' }])-const result = await executor.execute(createAccountInvocation())- expect(result.error).toContain('Team 1 not found')- })- 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)-- mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme-1' }])-- 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('CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET')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 posthogModule = require('~/common/utils/posthog')- const captureExceptionSpy = jest.spyOn(posthogModule, 'captureException')-- 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('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('rejects a null custom property value rather than queueing a clear', async () => {- disableAccountJwt()- const getTeamSpy = jest.spyOn(hub.teamManager, 'getTeam')-- mockExecHogForAsyncFunction('postHogSetAccountProperties', [- { external_id: 'acme-1', properties: { 'def-1': null } },- ])- const result = await executor.execute(createAccountInvocation())-- expect(result.error).toContain("received null for property 'def-1'")- expect(result.error).toContain('Use Clear property in the workflow editor')- expect(result.invocation.queueParameters).toBeUndefined()- expect(getTeamSpy).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' } },- ])-- const result = await executor.execute(createAccountInvocation())-- 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',- },- })+ expect(result.error).not.toContain('[')+ expect(fetchSpy).not.toHaveBeenCalled()})})diff --git a/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-tickets.template.test.ts b/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-tickets.template.test.tsindex 819f27b42457..70a29f1f17ff 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-tickets.template.test.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-tickets.template.test.ts@@ -2,18 +2,20 @@ import { TemplateTester } from '../../test/test-helpers'import { template as getTicketTemplate } from './posthog-get-ticket.template'import { template as updateTicketTemplate } from './posthog-update-ticket.template'+const TICKET_UUID = '0198a5c1-2f6e-7c3a-9b41-b6d21c0aa111'+describe('posthog conversations ticket templates', () => {const cases = [{name: 'get ticket',template: getTicketTemplate,- inputs: { ticket_id: 'ticket-1' },+ inputs: { ticket_id: TICKET_UUID },failurePrefix: 'Failed to fetch ticket (401):',},{name: 'update ticket',template: updateTicketTemplate,- inputs: { ticket_id: 'ticket-1', status: 'new' },+ inputs: { ticket_id: TICKET_UUID, status: 'new' },failurePrefix: 'Failed to update ticket (401):',},]@@ -26,32 +28,26 @@ describe('posthog conversations ticket templates', () => {})it('surfaces the API error body when the request fails', async () => {+ // A revoked ticket claim or unprovisioned secret is the common failure here, and+ // the bare status code alone gave the customer nothing to act on.+ tester.mockInternalFetchResponse({ status: 401, body: { error: 'Invalid API key' } })+let response = await tester.invoke(inputs)expect(response.error).toBeUndefined()- expect(response.finished).toBe(false)-- // A rotated or deleted secret API key is the common failure here, and the bare- // status code alone gave the customer nothing to act on.- response = await tester.invokeFetchResponse(response.invocation, {- status: 401,- body: { error: 'Invalid API key' },- })+ response = await tester.resumeInvocation(response.invocation)expect(response.error).toEqual(`${failurePrefix} Invalid API key`)})it('returns the ticket body on success', async () => {- let response = await tester.invoke(inputs)- expect(response.error).toBeUndefined()+ tester.mockInternalFetchResponse({ status: 200, body: { id: TICKET_UUID, status: 'new' } })- response = await tester.invokeFetchResponse(response.invocation, {- status: 200,- body: { id: 'ticket-1', status: 'new' },- })+ let response = await tester.invoke(inputs)+ response = await tester.resumeInvocation(response.invocation)expect(response.error).toBeUndefined()expect(response.finished).toBe(true)- expect(response.execResult).toEqual({ id: 'ticket-1', status: 'new' })+ expect(response.execResult).toEqual({ id: TICKET_UUID, status: 'new' })})})@@ -60,20 +56,20 @@ describe('posthog conversations ticket templates', () => {beforeEach(async () => {await tester.beforeEach()+ tester.mockInternalFetchResponse({ status: 200, body: { id: TICKET_UUID } })})- const fetchUrl = (response: Awaited<ReturnType<TemplateTester['invoke']>>): string =>- (response.invocation.queueParameters as { url: string }).url+ const fetchUrl = (): string => tester.mockInternalFetch.mock.calls[0][0] as stringit('does not request the field by default', async () => {- const response = await tester.invoke({ ticket_id: 'ticket-1' })- expect(fetchUrl(response)).not.toContain('include_first_customer_message_text')+ await tester.invoke({ ticket_id: TICKET_UUID })+ expect(fetchUrl()).not.toContain('include_first_customer_message_text')})it('appends the query param when opted in', async () => {- const response = await tester.invoke({ ticket_id: 'ticket-1', include_first_customer_message_text: true })- expect(fetchUrl(response)).toContain(- '/api/conversations/external/ticket/ticket-1?include_first_customer_message_text=true'+ await tester.invoke({ ticket_id: TICKET_UUID, include_first_customer_message_text: true })+ expect(fetchUrl()).toContain(+ `/internal/conversations/tickets/${TICKET_UUID}?include_first_customer_message_text=true`)})})diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-accounts.template.test.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-accounts.template.test.tsindex 6e80528f6e22..ca80ffc5333f 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-accounts.template.test.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-accounts.template.test.ts@@ -10,6 +10,9 @@ import { template as updateAccountTemplate } from './posthog-update-account.tempconst REL_UUID = '0197f9f0-1111-0000-0000-000000000000'+const sentBody = (tester: TemplateTester): any =>+ parseJSON((tester.mockInternalFetch.mock.calls[0][1] as { body: string }).body)+describe('posthog customer analytics account templates', () => {const cases = [{@@ -65,26 +68,23 @@ describe('posthog customer analytics account templates', () => {})it('surfaces the API error body when the request fails', async () => {- let response = await tester.invoke(inputs)- expect(response.error).toBeUndefined()- expect(response.finished).toBe(false)-- response = await tester.invokeFetchResponse(response.invocation, {+ tester.mockInternalFetchResponse({status: 400,body: { error: 'CSM: no relationship definition with this name' },})+ let response = await tester.invoke(inputs)+ expect(response.error).toBeUndefined()+ response = await tester.resumeInvocation(response.invocation)+expect(response.error).toEqual(`${failurePrefix} CSM: no relationship definition with this name`)})it('prints a readable line on success', async () => {- let response = await tester.invoke(inputs)- expect(response.error).toBeUndefined()+ tester.mockInternalFetchResponse({ status: 200, body: { id: 'account-id', external_id: 'acme-1' } })- response = await tester.invokeFetchResponse(response.invocation, {- status: 200,- body: { id: 'account-id', external_id: 'acme-1' },- })+ let response = await tester.invoke(inputs)+ response = await tester.resumeInvocation(response.invocation)expect(response.error).toBeUndefined()expect(response.finished).toBe(true)@@ -108,9 +108,10 @@ describe('posthog customer analytics account templates', () => {],['non-JSON body', 503, 'upstream connect error', 'Failed to update account (503): upstream connect error'],])('%s', async (_name, status, body, expected) => {- let response = await tester.invoke({ external_id: 'acme-1', tags: ['vip'] })+ tester.mockInternalFetchResponse({ status, body })- response = await tester.invokeFetchResponse(response.invocation, { status, body })+ let response = await tester.invoke({ external_id: 'acme-1', tags: ['vip'] })+ response = await tester.resumeInvocation(response.invocation)expect(response.error).toEqual(expected)})@@ -124,16 +125,12 @@ describe('posthog customer analytics account templates', () => {})it('logs the created line on 201', async () => {- let response = await tester.invoke({ external_id: 'acme-1' })+ tester.mockInternalFetchResponse({ status: 201, body: { id: 'account-id', external_id: 'acme-1' } })- const body = parseJSON((response.invocation.queueParameters as any).body)- expect(body).toEqual({ external_id: 'acme-1' })-- response = await tester.invokeFetchResponse(response.invocation, {- status: 201,- body: { id: 'account-id', external_id: 'acme-1' },- })+ let response = await tester.invoke({ external_id: 'acme-1' })+ response = await tester.resumeInvocation(response.invocation)+ expect(sentBody(tester)).toEqual({ external_id: 'acme-1' })expect(response.error).toBeUndefined()expect(response.finished).toBe(true)expect(response.logs.filter((log) => log.level === 'info').map((log) => log.message)).toContain(@@ -150,7 +147,7 @@ describe('posthog customer analytics account templates', () => {})})- describe('update account property queued fetch body', () => {+ describe('update account property request body', () => {const tester = new TemplateTester(updateAccountPropertyTemplate)beforeEach(async () => {@@ -158,16 +155,15 @@ describe('posthog customer analytics account templates', () => {})it('sends an explicit property clear as API null', async () => {+ tester.mockInternalFetchResponse({ status: 200, body: { external_id: 'acme-1' } })+const response = await tester.invoke({external_id: 'acme-1',properties: { '0197f9f0-0000-0000-0000-000000000000': { __posthog_clear_property: true } },})expect(response.error).toBeUndefined()- expect(response.finished).toBe(false)-- const body = parseJSON((response.invocation.queueParameters as any).body)- expect(body.properties).toEqual({ '0197f9f0-0000-0000-0000-000000000000': null })+ expect(sentBody(tester).properties).toEqual({ '0197f9f0-0000-0000-0000-000000000000': null })})it('rejects a property template that resolves to null', async () => {@@ -177,11 +173,11 @@ describe('posthog customer analytics account templates', () => {})expect(response.error).toContain("received null for property '0197f9f0-0000-0000-0000-000000000000'")- expect(response.invocation.queueParameters).toBeUndefined()+ expect(tester.mockInternalFetch).not.toHaveBeenCalled()})})- describe('update account relationships queued fetch body', () => {+ describe('update account relationships request body', () => {const tester = new TemplateTester(updateAccountRelationshipsTemplate)beforeEach(async () => {@@ -189,16 +185,15 @@ describe('posthog customer analytics account templates', () => {})it('sends relationship assignments keyed by UUID in the request body', async () => {+ tester.mockInternalFetchResponse({ status: 200, body: { external_id: 'acme-1' } })+const response = await tester.invoke({external_id: 'acme-1',relationships: { [REL_UUID]: { type: 'user', id: 42 } },})expect(response.error).toBeUndefined()- expect(response.finished).toBe(false)-- const body = parseJSON((response.invocation.queueParameters as any).body)- expect(body.relationships).toEqual({ [REL_UUID]: { type: 'user', id: 42 } })+ expect(sentBody(tester).relationships).toEqual({ [REL_UUID]: { type: 'user', id: 42 } })})})})diff --git a/nodejs/src/cdp/templates/test/test-helpers.ts b/nodejs/src/cdp/templates/test/test-helpers.tsindex b0f27558cf95..0f78d88d7e5e 100644--- a/nodejs/src/cdp/templates/test/test-helpers.ts+++ b/nodejs/src/cdp/templates/test/test-helpers.ts@@ -179,10 +179,9 @@ export class TemplateTester {public mockFetch = jest.fn()public mockPrint = jest.fn()- // Async functions (postHogGetAccount, postHogGetTicket, ...) resolve the team to read- // its secret_api_token — stub it so templates built on them are testable.+ public mockInternalFetch = jest.fn()public mockTeamManager = {- getTeam: jest.fn().mockResolvedValue({ id: 1, secret_api_token: 'test-secret-token' }),+ getTeam: jest.fn().mockResolvedValue({ id: 1 }),}constructor(private _template: HogFunctionTemplate,@@ -238,11 +237,14 @@ export class TemplateTester {},{teamManager: this.mockTeamManager as any,- // Disabled on purpose: template tests pin Hog response handling, and- // 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, ''),+ conversationsTicketsJwt: new ScopedServiceJwt(+ PosthogJwtAudience.CONVERSATIONS_TICKETS,+ config.CONVERSATIONS_TICKETS_JWT_SECRET+ ),+ customerAnalyticsAccountsJwt: new ScopedServiceJwt(+ PosthogJwtAudience.CUSTOMER_ANALYTICS_ACCOUNTS,+ config.CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET+ ),hogInputsService,emailService,recipientTokensService,@@ -261,6 +263,8 @@ export class TemplateTester {*/async beforeEach() {Settings.defaultZone = 'UTC'+ const requestModule = require('~/common/utils/request')+ jest.spyOn(requestModule, 'internalFetch').mockImplementation(this.mockInternalFetch)if (!this.geoipService) {this.geoipService = new GeoIPService(defaultConfig.MMDB_FILE_LOCATION)}@@ -414,6 +418,18 @@ export class TemplateTester {return this.hogExecutor.execute(invocation)}+ // Set before invoke(): the internal-route handler consumes it inline, then the VM+ // pauses — resume with resumeInvocation to run the Hog code after the call.+ mockInternalFetchResponse(response: { status: number; body: unknown }): void {+ this.mockInternalFetch.mockResolvedValue({+ status: response.status,+ headers: {},+ text: () => Promise.resolve(JSON.stringify(response.body)),+ json: () => Promise.resolve(response.body),+ dump: () => Promise.resolve(),+ })+ }+async invokeFetchResponse(invocation: CyclotronJobInvocationHogFunction,response: { status: number; body: unknown }diff --git a/nodejs/tests/fixtures/hog-bytecode/956743331887135bb796230fcd6888e07afe23a4c587f95f499f0da949b72a5c.json b/nodejs/tests/fixtures/hog-bytecode/956743331887135bb796230fcd6888e07afe23a4c587f95f499f0da949b72a5c.jsonnew file mode 100644index 000000000000..9db255bc7bba--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/956743331887135bb796230fcd6888e07afe23a4c587f95f499f0da949b72a5c.json@@ -0,0 +1 @@+["_H",1,32,"0198a5c1-2f6e-7c3a-9b41-b6d21c0aa111",38]