: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 conversations ticket actions (#90561)
Patricio6e76826f8878
diff --git a/nodejs/src/cdp/async-function-registry.ts b/nodejs/src/cdp/async-function-registry.tsindex 5afcfba03866..a4ad0717fbad 100644--- a/nodejs/src/cdp/async-function-registry.ts+++ b/nodejs/src/cdp/async-function-registry.ts@@ -6,12 +6,22 @@ import {HogFunctionInvocationGlobalsWithInputs,MinimalLogEntry,} from './types'+import { ScopedServiceJwt } from './utils/scoped-service-jwt'export type AsyncFunctionContext = {invocation: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>['invocation']globals: HogFunctionInvocationGlobalsWithInputsteamManager: TeamManagersiteUrl: string+ // In-cluster Django base URL for /api/projects/<team_id>/internal/... routes, which+ // Contour blocks from the public internet. Only first-party handlers may call it.+ internalApiBaseUrl: string+ conversationsTicketsJwt: 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.+ // Throws once the budget is exhausted. A no-op for callers that don't enforce a budget.+ consumeInlineAsyncBudget: () => void}export type AsyncFunctionHandler = {diff --git a/nodejs/src/cdp/async-functions/conversations.ts b/nodejs/src/cdp/async-functions/conversations.tsindex 16d1d9cf2a41..5a5885f876f6 100644--- a/nodejs/src/cdp/async-functions/conversations.ts+++ b/nodejs/src/cdp/async-functions/conversations.ts@@ -3,11 +3,41 @@ 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).+ */+async function callInternalTicketApi(+ context: AsyncFunctionContext,+ result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,+ ticketId: string,+ options: { method: 'GET' | 'PATCH'; body?: string; extraHeaders?: Record<string, string> }+): Promise<void> {+ // 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.+ if (!UUID_RE.test(ticketId)) {+ throw new Error(`[HogFunction] - ticket_id must be a UUID, got '${ticketId}'`)+ }+ const canonicalTicketId = ticketId.toLowerCase()+ await callInternalApi(context, result, {+ jwt: context.conversationsTicketsJwt,+ path: `/api/projects/${context.invocation.teamId}/internal/conversations/tickets/${canonicalTicketId}`,+ entityClaims: { ticket_id: canonicalTicketId },+ ...options,+ })+}+registerAsyncFunction('postHogGetTicket', {execute: async (args, context, result) => {const [opts] = args as [Record<string, any> | undefined]@@ -17,6 +47,13 @@ registerAsyncFunction('postHogGetTicket', {throw new Error("[HogFunction] - postHogGetTicket call missing 'ticket_id' property")}+ 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' })+ return+ }+const team = await getTeamWithSecretToken(context, 'postHogGetTicket', TICKET_ACTIONS)result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({@@ -81,29 +118,35 @@ registerAsyncFunction('postHogUpdateTicket', {throw new Error("[HogFunction] - postHogUpdateTicket call missing 'ticket_id' property")}- const updateTeam = await getTeamWithSecretToken(context, 'postHogUpdateTicket', TICKET_ACTIONS)-- const headers: Record<string, string> = {- 'Content-Type': 'application/json',- Authorization: `Bearer ${updateTeam.secret_api_token}`,- }-// Present only when running inside a HogFlow (spread onto the synthesized invocation);// forward the workflow id so the ticket activity log can attribute and link to it. 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.const hogFlow = (context.invocation as { hogFlow?: HogFlow }).hogFlow- if (hogFlow?.id) {- headers['X-PostHog-Hog-Flow-Id'] = hogFlow.id+ const 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}`,method: 'PATCH',body: JSON.stringify(updates),- headers,+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${updateTeam.secret_api_token}`,+ ...hogFlowHeaders,+ },})},diff --git a/nodejs/src/cdp/async-functions/internal-api-call.ts b/nodejs/src/cdp/async-functions/internal-api-call.tsnew file mode 100644index 000000000000..90f4fba540e5--- /dev/null+++ b/nodejs/src/cdp/async-functions/internal-api-call.ts@@ -0,0 +1,152 @@+import { DateTime } from 'luxon'++import { parseJSON } from '~/common/utils/json-parse'+import { internalFetch } from '~/common/utils/request'++import { AsyncFunctionContext } from '../async-function-registry'+import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult } from '../types'+import { RETRIABLE_STATUS_CODES, fetchErrorDetail } from '../utils/cdp-fetch'+import { ScopedServiceJwt } from '../utils/scoped-service-jwt'++export const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i++// Rolling deploys drop in-flight connections, so one quick retry round matters; anything+// longer would block the consumer loop, which is why the queued-fetch path exists for+// third-party calls.+const MAX_ATTEMPTS = 3+const BACKOFF_MS = 250+// Same statuses the queued-fetch path retries (cdp-fetch.ts), so a transient Django 500+// gets the same resilience here that it would have gotten through executeFetch.+const RETRIABLE_STATUSES = RETRIABLE_STATUS_CODES++/**+ * Calls an internal-only Django route (/api/projects/<team_id>/internal/...) on behalf of a+ * first-party async function, and pushes the `{status, body}` response onto the resumed VM+ * stack (see the RETURN-VALUE CONTRACT in example.ts).+ *+ * Runs inline instead of through queueParameters on purpose:+ * - the queued-fetch executor's SSRF guard refuses in-cluster hosts, and exempting them+ * would hand that bypass to user-settable queue data;+ * - nothing is persisted, so no credential ever lands in a job row — a fresh short-lived+ * token is minted per attempt (same reasoning as the SigV4 signing in executeFetch).+ *+ * The team claim always comes from the invocation, never from Hog-provided arguments.+ */+export async function callInternalApi(+ context: AsyncFunctionContext,+ result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,+ options: {+ jwt: ScopedServiceJwt+ path: `/${string}`+ method: 'GET' | 'PATCH' | 'POST'+ entityClaims: Record<string, string>+ body?: string+ extraHeaders?: Record<string, string>+ }+): Promise<void> {+ const { jwt, path, method, entityClaims, body, extraHeaders } = options+ const startedAt = performance.now()++ // Counts once per handler call, not per retry attempt below: the retries are all one+ // logical step from the VM's point of view, and the counted queued-fetch path only+ // counts once per queued fetch too.+ context.consumeInlineAsyncBudget()++ const parseBody = (text: string | null): unknown => {+ try {+ return text ? parseJSON(text) : undefined+ } catch {+ // Non-JSON body passes through as text+ return text+ }+ }++ let response: { status: number; body: unknown } | null = null++ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {+ // Fresh token per attempt: nothing stored, nothing reusable after the short TTL.+ // team_id spreads last so no entityClaims value can ever override the trusted team.+ const token = jwt.mint({ ...entityClaims, team_id: context.invocation.teamId })++ let fetchError: Error | null = null+ let status: number | null = null+ let text: string | null = null+ try {+ const fetchResponse = await internalFetch(`${context.internalApiBaseUrl}${path}`, {+ method,+ headers: {+ 'Content-Type': 'application/json',+ ...extraHeaders,+ Authorization: `Bearer ${token}`,+ },+ ...(body !== undefined ? { body } : {}),+ })+ status = fetchResponse.status+ text = await fetchResponse.text()+ } catch (err) {+ // Covers both a failed fetch (status stays null) and a body-read failure after a+ // successful status line (status is set but the response can't be trusted) — either+ // way this attempt did not complete, so it must not be treated as a success below.+ fetchError = err as Error+ }++ const succeeded = fetchError === null && status !== null && !RETRIABLE_STATUSES.includes(status)+ if (succeeded) {+ const parsedBody = parseBody(text)+ if (status! >= 400) {+ result.logs.push({+ level: 'error',+ timestamp: DateTime.now(),+ message: `Internal API call failed with status code ${status}.`,+ })+ }+ response = { status: status!, body: parsedBody }+ break+ }++ const willRetry = attempt < MAX_ATTEMPTS+ result.logs.push({+ level: willRetry ? 'info' : 'error',+ timestamp: DateTime.now(),+ message:+ `Internal API call failed on attempt ${attempt} with status code ${status ?? '(none)'}.` ++ (fetchError ? ` Error: ${fetchErrorDetail(fetchError)}.` : '') ++ (willRetry ? ' Retrying.' : ''),+ })++ if (!willRetry) {+ if (status !== null && fetchError === null) {+ // A real HTTP response came back (a retriable status like 503) and its body was+ // read cleanly — keep it so templates and logs still see what upstream said,+ // matching what executeFetch preserves on its own final failing attempt.+ response = { status, body: parseBody(text) }+ } else {+ // Same shape executeFetch pushes on a client-side failure, so template guards+ // like `if (response.status != 200) throw` keep firing. Also covers a body-read+ // failure after a 200 header: without fetchError === null above, that never+ // reaches the success branch and lands here as a proper failure instead of a+ // silently empty 200.+ response = {+ status: 500,+ body: fetchError ? `${fetchError.name}: ${fetchErrorDetail(fetchError)}` : undefined,+ }+ }+ break+ }+ await new Promise((resolve) => setTimeout(resolve, BACKOFF_MS * attempt))+ }++ result.invocation.state.timings.push({+ kind: 'async_function',+ duration_ms: Math.round(performance.now() - startedAt),+ })+ result.metrics.push({+ team_id: context.invocation.teamId,+ app_source_id: context.invocation.parentRunId ?? context.invocation.functionId,+ metric_kind: 'other',+ metric_name: 'fetch',+ count: 1,+ })++ result.invocation.state.vmState?.stack.push(response)+}diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex 047dda0e1524..cbc25a5ff830 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -50,6 +50,8 @@ import { WarehouseWebhooksService } from './services/warehouse/warehouse-webhookimport { MAX_FETCH_TIMEOUT_MS, cdpTrackedFetch } from './utils/cdp-fetch'import { configureValkeyReads } from './utils/dual-store'import { EncryptedFields } from './utils/encryption-utils'+import { PosthogJwtAudience } from './utils/jwt-utils'+import { ScopedServiceJwt } from './utils/scoped-service-jwt'/** Union of every output name resolved by `createCdpOutputsRegistry()`. */export type CdpOutput = AppMetricsOutput | LogEntriesOutput | HogInvocationResultsOutput | WarehouseSourceWebhooksOutput@@ -110,7 +112,12 @@ export interface CdpCoreServices {export type CdpCoreServicesConfig = Pick<CommonConfig,- 'REDIS_URL' | 'REDIS_POOL_MIN_SIZE' | 'REDIS_POOL_MAX_SIZE' | 'ENCRYPTION_SALT_KEYS' | 'SITE_URL'+ | 'REDIS_URL'+ | 'REDIS_POOL_MIN_SIZE'+ | 'REDIS_POOL_MAX_SIZE'+ | 'ENCRYPTION_SALT_KEYS'+ | 'SITE_URL'+ | 'INTERNAL_API_BASE_URL'> &UsageIngestionConfig &Pick<@@ -150,6 +157,7 @@ export type CdpCoreServicesConfig = Pick<| 'SES_UNTRACKED_CONFIGURATION_SET'| 'EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD'| 'CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN'+ | 'CONVERSATIONS_TICKETS_JWT_SECRET'| 'CDP_FETCH_RETRIES'| 'CDP_FETCH_BACKOFF_BASE_MS'| 'CDP_FETCH_BACKOFF_MAX_MS'@@ -456,9 +464,14 @@ export function createCdpCoreServices(fetchBackoffBaseMs: config.CDP_FETCH_BACKOFF_BASE_MS,fetchBackoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,siteUrl: config.SITE_URL,+ internalApiBaseUrl: config.INTERNAL_API_BASE_URL,},{teamManager: deps.teamManager,+ conversationsTicketsJwt: new ScopedServiceJwt(+ PosthogJwtAudience.CONVERSATIONS_TICKETS,+ config.CONVERSATIONS_TICKETS_JWT_SECRET+ ),hogInputsService,emailService,recipientTokensService,diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex 6a6842d38ef5..8e182ec6ae1e 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -170,6 +170,7 @@ export type CdpConfig = ClickhouseConfig & {// newest first (first signs, all verify). Deliberately NOT the fleet-wide INTERNAL_API_SECRET// (see .agents/security.md): empty in prod means the route fails closed until provisioned.WORKFLOWS_RESCHEDULE_JWT_SECRET: string+ CONVERSATIONS_TICKETS_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@@ -334,6 +335,9 @@ export function getDefaultCdpConfig(): CdpConfig {// mass wake, so wakes are trickled (500k parked @ 200/s ≈ 42 min spread).// Dev/test default must match Django's (posthog/settings/data_stores.py).WORKFLOWS_RESCHEDULE_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-workflows-reschedule-jwt' : '',+ // 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/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 e1b309e7d240..a7231afb8585 100644--- a/nodejs/src/cdp/services/hog-executor-async.service.ts+++ b/nodejs/src/cdp/services/hog-executor-async.service.ts@@ -21,6 +21,7 @@ import { resolveAwsSigV4Credentials, signAwsRequest } from '../utils/aws-sigv4'import { cdpTrackedFetch, fetchErrorDetail, isFetchResponseRetriable } from '../utils/cdp-fetch'import { createInvocationResult } from '../utils/invocation-utils'import { isNonFailureStatus } from '../utils/non-failure-status-codes'+import { ScopedServiceJwt } from '../utils/scoped-service-jwt'import { HogExecutorExecuteOptions, HogExecutorPreviousResult, HogExecutorService } from './hog-executor.service'import { HogInputsService } from './hog-inputs.service'import { EMAIL_QUEUE_PRIORITY, getEmailQueuePriorityClass } from './messaging/email-priority'@@ -48,6 +49,7 @@ export interface HogExecutorAsyncConfig {fetchBackoffBaseMs: numberfetchBackoffMaxMs: numbersiteUrl: string+ internalApiBaseUrl: string}/**@@ -57,6 +59,7 @@ export interface HogExecutorAsyncConfig {*/export interface HogExecutorAsyncDependencies {teamManager: TeamManager+ conversationsTicketsJwt: ScopedServiceJwthogInputsService: HogInputsServiceemailService: EmailServicerecipientTokensService: RecipientTokensService@@ -97,6 +100,20 @@ export class HogExecutorAsyncService {let asyncFunctionCount = 0const maxAsyncFunctions = options?.maxAsyncFunctions ?? 1+ // Shared with inline async handlers (see AsyncFunctionContext.consumeInlineAsyncBudget):+ // they do real network I/O without ever setting queueParameters, so the queued-type+ // counting below never sees them. Without this they could run unbounded up to the VM's+ // own step cap, each holding this worker slot for the full retry round instead of+ // rescheduling like a queued fetch does.+ const consumeInlineAsyncBudget = (): void => {+ asyncFunctionCount+++ if (asyncFunctionCount > maxAsyncFunctions) {+ throw new Error(+ `Max async functions reached: ${maxAsyncFunctions}. This function performed too many API calls in a single execution.`+ )+ }+ }+let result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> | null = nullconst metrics: MinimalAppMetric[] = []const logs: MinimalLogEntry[] = []@@ -174,7 +191,12 @@ export class HogExecutorAsyncService {// Finish execution, carrying forward previous execResult// Tricky: We don't pass metrics in previousResult as they're accumulated in the local metrics arrayconst { metrics: _m, logs: _l, ...previousResultWithoutMetrics } = result || {}- result = await this.execute(nextInvocation, options, previousResultWithoutMetrics)+ result = await this.execute(+ nextInvocation,+ options,+ previousResultWithoutMetrics,+ consumeInlineAsyncBudget+ )}logs.push(...result.logs)@@ -207,7 +229,10 @@ export class HogExecutorAsyncService {async execute(invocation: CyclotronJobInvocationHogFunction,options: HogExecutorExecuteOptions = {},- previousResult: HogExecutorPreviousResult = {}+ previousResult: HogExecutorPreviousResult = {},+ // Callers outside executeWithAsyncFunctions' loop (e.g. the source-webhooks consumer)+ // run at most one async step per execute() call already, so a no-op budget is safe there.+ consumeInlineAsyncBudget: () => void = () => {}): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>> {return this.hogExecutor.execute(invocation,@@ -242,6 +267,9 @@ export class HogExecutorAsyncService {globals,teamManager: this.deps.teamManager,siteUrl: this.config.siteUrl,+ internalApiBaseUrl: this.config.internalApiBaseUrl,+ conversationsTicketsJwt: this.deps.conversationsTicketsJwt,+ consumeInlineAsyncBudget,},result)diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.tsindex 5fb256be6188..dd22b7a7599f 100644--- a/nodejs/src/cdp/services/hog-executor.service.test.ts+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts@@ -1,4 +1,7 @@// sort-imports-ignore+import { PosthogJwtAudience } from '~/cdp/utils/jwt-utils'+import { ScopedServiceJwt } from '~/cdp/utils/scoped-service-jwt'+import { FetchOptions } from '~/common/utils/request'import { createServer } from 'http'import { DateTime } from 'luxon'import { AddressInfo } from 'net'@@ -91,9 +94,14 @@ describe('Hog Executor', () => {fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,siteUrl: hub.SITE_URL,+ internalApiBaseUrl: hub.INTERNAL_API_BASE_URL,},{teamManager: hub.teamManager,+ conversationsTicketsJwt: new ScopedServiceJwt(+ PosthogJwtAudience.CONVERSATIONS_TICKETS,+ hub.CONVERSATIONS_TICKETS_JWT_SECRET+ ),hogInputsService,emailService,recipientTokensService,@@ -623,122 +631,328 @@ describe('Hog Executor', () => {{ inputs: {} })- it('postHogGetTicket queues internal fetch with correct params', async () => {- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({- id: 1,- secret_api_token: 'test-secret-token',- } as any)+ const TICKET_UUID = '0198a5c1-2f6e-7c3a-9b41-b6d21c0aa111'+ const requestModule = require('~/common/utils/request')- mockExecHogForAsyncFunction('postHogGetTicket', [{ ticket_id: 'test-ticket-123' }])+ 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(createTicketInvocation())+ // 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 disableTicketJwt = () => {+ ;(executor as any).deps.conversationsTicketsJwt = new ScopedServiceJwt(+ PosthogJwtAudience.CONVERSATIONS_TICKETS,+ ''+ )+ }- 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' },+ describe('scoped JWT path', () => {+ it('postHogGetTicket mints a team+ticket pinned token for the internal route and needs no team secret', async () => {+ const fetchSpy = jest+ .spyOn(requestModule, 'internalFetch')+ .mockResolvedValue(mockInternalResponse(200, { id: TICKET_UUID, status: 'new' }))+ const getTeamSpy = jest.spyOn(hub.teamManager, 'getTeam')++ mockExecHogForAsyncFunction('postHogGetTicket', [{ ticket_id: TICKET_UUID }])+ const result = await executor.execute(createTicketInvocation())++ expect(fetchSpy).toHaveBeenCalledTimes(1)+ const [url, options] = fetchSpy.mock.calls[0] as unknown as [string, FetchOptions]+ expect(url).toEqual(+ `${hub.INTERNAL_API_BASE_URL}/api/projects/1/internal/conversations/tickets/${TICKET_UUID}`+ )+ expect(options.method).toEqual('GET')++ const headers = options.headers as Record<string, string>+ const token = headers['Authorization'].replace('Bearer ', '')+ const claims = new ScopedServiceJwt(+ PosthogJwtAudience.CONVERSATIONS_TICKETS,+ hub.CONVERSATIONS_TICKETS_JWT_SECRET+ ).verify(token)+ expect(claims.team_id).toEqual(1)+ expect(claims.ticket_id).toEqual(TICKET_UUID)+ expect(claims.exp! - claims.iat!).toEqual(5 * 60)++ expect(result.invocation.state.vmState!.stack).toEqual([+ { status: 200, body: { id: TICKET_UUID, status: 'new' } },+ ])+ // 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('postHogUpdateTicket queues internal fetch with correct params', async () => {- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({- id: 1,- secret_api_token: 'test-secret-token',- } as any)+ it('postHogUpdateTicket forwards the updates body and workflow attribution header', async () => {+ const fetchSpy = jest+ .spyOn(requestModule, 'internalFetch')+ .mockResolvedValue(mockInternalResponse(200, { ok: true }))- mockExecHogForAsyncFunction('postHogUpdateTicket', [- { ticket_id: 'test-ticket-456', updates: { status: 'resolved', priority: 'high' } },- ])+ mockExecHogForAsyncFunction('postHogUpdateTicket', [+ { ticket_id: TICKET_UUID, updates: { status: 'resolved', priority: 'high' } },+ ])+ const invocation = createTicketInvocation()+ ;(invocation as any).hogFlow = { id: 'flow-123' }+ await executor.execute(invocation)- const result = await executor.execute(createTicketInvocation())+ const [, options] = fetchSpy.mock.calls[0] as unknown as [string, FetchOptions]+ expect(options.method).toEqual('PATCH')+ expect(options.body).toEqual(JSON.stringify({ status: 'resolved', priority: 'high' }))+ expect((options.headers as Record<string, string>)['X-PostHog-Hog-Flow-Id']).toEqual('flow-123')+ })- 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.each(['test-ticket-123', '../../../admin', `${TICKET_UUID}/extra`])(+ 'refuses a non-UUID ticket_id (%s) before any token is minted',+ async (badTicketId) => {+ const fetchSpy = jest.spyOn(requestModule, 'internalFetch')++ mockExecHogForAsyncFunction('postHogGetTicket', [{ ticket_id: badTicketId }])+ const result = await executor.execute(createTicketInvocation())++ expect(result.error).toContain('must be a UUID')+ expect(fetchSpy).not.toHaveBeenCalled()+ }+ )++ it('lowercases a mixed-case ticket_id for the URL and the claim', async () => {+ const fetchSpy = jest+ .spyOn(requestModule, 'internalFetch')+ .mockResolvedValue(mockInternalResponse(200, { id: TICKET_UUID }))++ mockExecHogForAsyncFunction('postHogGetTicket', [{ ticket_id: TICKET_UUID.toUpperCase() }])+ await executor.execute(createTicketInvocation())++ const [url, options] = fetchSpy.mock.calls[0] as unknown as [string, FetchOptions]+ expect(url).toContain(`/tickets/${TICKET_UUID}`)+ const headers = options.headers as Record<string, string>+ const claims = new ScopedServiceJwt(+ PosthogJwtAudience.CONVERSATIONS_TICKETS,+ hub.CONVERSATIONS_TICKETS_JWT_SECRET+ ).verify(headers['Authorization'].replace('Bearer ', ''))+ expect(claims.ticket_id).toEqual(TICKET_UUID)})- })- it('postHogGetTicket errors when ticket_id is missing', async () => {- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({- id: 1,- secret_api_token: 'test-secret-token',- } as any)+ it('passes a 4xx through to the Hog response without retrying', async () => {+ const fetchSpy = jest+ .spyOn(requestModule, 'internalFetch')+ .mockResolvedValue(mockInternalResponse(404, { error: 'Ticket not found' }))- mockExecHogForAsyncFunction('postHogGetTicket', [{}])+ mockExecHogForAsyncFunction('postHogGetTicket', [{ ticket_id: TICKET_UUID }])+ const result = await executor.execute(createTicketInvocation())- const result = await executor.execute(createTicketInvocation())- expect(result.error).toContain("missing 'ticket_id'")- })+ expect(fetchSpy).toHaveBeenCalledTimes(1)+ expect(result.invocation.state.vmState!.stack).toEqual([+ { status: 404, body: { error: 'Ticket not found' } },+ ])+ })- it('postHogUpdateTicket errors when ticket_id is missing', async () => {- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({- id: 1,- secret_api_token: 'test-secret-token',- } as any)+ it('retries a dropped connection and returns the eventual response', async () => {+ const fetchSpy = jest+ .spyOn(requestModule, 'internalFetch')+ .mockRejectedValueOnce(new Error('socket hang up'))+ .mockResolvedValue(mockInternalResponse(200, { id: TICKET_UUID }))- mockExecHogForAsyncFunction('postHogUpdateTicket', [{ updates: { status: 'resolved' } }])+ mockExecHogForAsyncFunction('postHogGetTicket', [{ ticket_id: TICKET_UUID }])+ const result = await executor.execute(createTicketInvocation())- const result = await executor.execute(createTicketInvocation())- expect(result.error).toContain("missing 'ticket_id'")- })+ expect(fetchSpy).toHaveBeenCalledTimes(2)+ expect(result.invocation.state.vmState!.stack).toEqual([{ status: 200, body: { id: TICKET_UUID } }])+ expect(result.logs.some((log) => log.message.includes('Retrying'))).toBe(true)+ })- it('postHogGetTicket errors when team is not found', async () => {- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue(null)+ it('pushes a status-500 response after exhausting connection retries', async () => {+ const fetchSpy = jest+ .spyOn(requestModule, 'internalFetch')+ .mockRejectedValue(new Error('connect ECONNREFUSED'))- mockExecHogForAsyncFunction('postHogGetTicket', [{ ticket_id: 'test-ticket-123' }])+ mockExecHogForAsyncFunction('postHogGetTicket', [{ ticket_id: TICKET_UUID }])+ const result = await executor.execute(createTicketInvocation())- const result = await executor.execute(createTicketInvocation())- expect(result.error).toContain('Team 1 not found')- })+ expect(fetchSpy).toHaveBeenCalledTimes(3)+ const [pushed] = result.invocation.state.vmState!.stack as [{ status: number; body: string }]+ expect(pushed.status).toEqual(500)+ expect(pushed.body).toContain('ECONNREFUSED')+ })- 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) => {- jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({- id: 1,- secret_api_token: null,- } as any)+ it('retries and then fails loudly when the body stream fails after a 200 header', async () => {+ const fetchSpy = jest.spyOn(requestModule, 'internalFetch').mockResolvedValue({+ status: 200,+ headers: {},+ text: () => Promise.reject(new Error('other side closed')),+ json: () => Promise.reject(new Error('other side closed')),+ dump: () => Promise.resolve(),+ })- mockExecHogForAsyncFunction(name, [args])+ mockExecHogForAsyncFunction('postHogGetTicket', [{ ticket_id: TICKET_UUID }])+ const result = await executor.execute(createTicketInvocation())- 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('ticket workflow actions')- expect(result.error).toContain('Settings > Support > Secret API key')- expect(result.error).not.toContain('[')+ // A 200 header with an unreadable body is not a success: it retries like any+ // other failed attempt instead of silently returning an empty ticket.+ expect(fetchSpy).toHaveBeenCalledTimes(3)+ const [pushed] = result.invocation.state.vmState!.stack as [{ status: number; body: string }]+ expect(pushed.status).toEqual(500)+ expect(pushed.body).toContain('other side closed')+ })++ it('preserves the upstream body on the final attempt of a retriable status', async () => {+ const fetchSpy = jest+ .spyOn(requestModule, 'internalFetch')+ .mockResolvedValue(mockInternalResponse(503, { error: 'database unavailable' }))++ mockExecHogForAsyncFunction('postHogGetTicket', [{ ticket_id: TICKET_UUID }])+ const result = await executor.execute(createTicketInvocation())++ expect(fetchSpy).toHaveBeenCalledTimes(3)+ expect(result.invocation.state.vmState!.stack).toEqual([+ { status: 503, body: { error: 'database unavailable' } },+ ])+ })++ it('retries a transient 500 the same way the legacy fetch path does', async () => {+ const fetchSpy = jest+ .spyOn(requestModule, 'internalFetch')+ .mockResolvedValueOnce(mockInternalResponse(500, { error: 'boom' }))+ .mockResolvedValue(mockInternalResponse(200, { id: TICKET_UUID }))++ mockExecHogForAsyncFunction('postHogGetTicket', [{ ticket_id: TICKET_UUID }])+ const result = await executor.execute(createTicketInvocation())++ expect(fetchSpy).toHaveBeenCalledTimes(2)+ expect(result.invocation.state.vmState!.stack).toEqual([{ status: 200, body: { id: TICKET_UUID } }])+ })++ it('rejects a second inline ticket call once the per-invocation async budget is spent', async () => {+ const fetchSpy = jest+ .spyOn(requestModule, 'internalFetch')+ .mockResolvedValue(mockInternalResponse(200, { id: TICKET_UUID }))++ const bytecode = await compileHog(`+ let a := postHogGetTicket({'ticket_id': '${TICKET_UUID}'})+ let b := postHogGetTicket({'ticket_id': '${TICKET_UUID}'})+ return b+ `)+ const invocation = createExampleInvocation(createHogFunction({ bytecode }), { inputs: {} })++ const result = await executor.executeWithAsyncFunctions(invocation)++ // Neither ticket call sets queueParameters, so without a shared budget both+ // would run inline in the same worker slot regardless of maxAsyncFunctions.+ expect(fetchSpy).toHaveBeenCalledTimes(1)+ expect(result.error).toContain('Max async functions reached')+ expect(result.finished).toBe(true)+ })})- it('captures exception with team_id when the ticket 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('postHogGetTicket 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)- const posthogModule = require('~/common/utils/posthog')- const captureExceptionSpy = jest.spyOn(posthogModule, 'captureException')+ mockExecHogForAsyncFunction('postHogGetTicket', [{ ticket_id: 'test-ticket-123' }])- mockExecHogForAsyncFunction('postHogUpdateTicket', [- { ticket_id: 'test-ticket-456', updates: { status: 'new' } },- ])- await executor.execute(createTicketInvocation())+ const result = await executor.execute(createTicketInvocation())- expect(captureExceptionSpy).toHaveBeenCalledWith(- expect.any(Error),- expect.objectContaining({- tags: expect.objectContaining({ team_id: 1, function: 'postHogUpdateTicket' }),+ 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 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('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' }),+ })+ )+ })+ })++ it.each(['postHogGetTicket', 'postHogUpdateTicket'])('%s errors when ticket_id is missing', async (name) => {+ mockExecHogForAsyncFunction(name, [name === 'postHogUpdateTicket' ? { updates: { status: 'new' } } : {}])++ const result = await executor.execute(createTicketInvocation())+ expect(result.error).toContain("missing 'ticket_id'")})})diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.tsindex 4d05e19b77c7..56e60d11bbf1 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts@@ -7,6 +7,8 @@ import { insertHogFunctionTemplate, insertIntegration } from '~/cdp/_tests/fixtuimport { createExampleHogFlowInvocation } from '~/cdp/_tests/fixtures-hogflows'import { HogFlowAction } from '~/cdp/schema/hogflow'import { createInvocationResult } from '~/cdp/utils/invocation-utils'+import { PosthogJwtAudience } from '~/cdp/utils/jwt-utils'+import { ScopedServiceJwt } from '~/cdp/utils/scoped-service-jwt'import { closeHub, createHub } from '~/common/utils/db/hub'import { parseJSON } from '~/common/utils/json-parse'import { createTestTeamFixture } from '~/tests/helpers/sql'@@ -79,9 +81,14 @@ describe('HogFunctionHandler', () => {fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,siteUrl: hub.SITE_URL,+ internalApiBaseUrl: hub.INTERNAL_API_BASE_URL,},{teamManager: hub.teamManager,+ conversationsTicketsJwt: new ScopedServiceJwt(+ PosthogJwtAudience.CONVERSATIONS_TICKETS,+ hub.CONVERSATIONS_TICKETS_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 5c3f39356e37..fda3d406e711 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts@@ -1,4 +1,6 @@// sort-imports-ignore+import { PosthogJwtAudience } from '~/cdp/utils/jwt-utils'+import { ScopedServiceJwt } from '~/cdp/utils/scoped-service-jwt'import { DateTime, Duration } from 'luxon'import { FixtureHogFlowBuilder, SimpleHogFlowRepresentation } from '~/cdp/_tests/builders/hogflow.builder'@@ -101,9 +103,14 @@ describe('Hogflow Executor', () => {fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,siteUrl: hub.SITE_URL,+ internalApiBaseUrl: hub.INTERNAL_API_BASE_URL,},{teamManager: hub.teamManager,+ conversationsTicketsJwt: new ScopedServiceJwt(+ PosthogJwtAudience.CONVERSATIONS_TICKETS,+ hub.CONVERSATIONS_TICKETS_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 1414f834bf58..c746c9ddce39 100644--- a/nodejs/src/cdp/templates/test/test-helpers.ts+++ b/nodejs/src/cdp/templates/test/test-helpers.ts@@ -7,6 +7,8 @@ import { CyclotronInputType } from '~/cdp/schema/cyclotron'import { formatLiquidInput } from '~/cdp/services/hog-inputs.service'import { NativeDestinationExecutorService } from '~/cdp/services/native-destination-executor.service'import { isNativeHogFunction } from '~/cdp/utils'+import { PosthogJwtAudience } from '~/cdp/utils/jwt-utils'+import { ScopedServiceJwt } from '~/cdp/utils/scoped-service-jwt'import { defaultConfig } from '~/common/config/config'import { GeoIPService, GeoIp } from '~/common/utils/geoip'@@ -225,9 +227,14 @@ export class TemplateTester {fetchBackoffBaseMs: config.CDP_FETCH_BACKOFF_BASE_MS,fetchBackoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,siteUrl: config.SITE_URL,+ internalApiBaseUrl: config.INTERNAL_API_BASE_URL,},{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, ''),hogInputsService,emailService,recipientTokensService,diff --git a/nodejs/src/cdp/utils/jwt-utils.ts b/nodejs/src/cdp/utils/jwt-utils.tsindex 6ccdeea6cefa..1c33c5386e60 100644--- a/nodejs/src/cdp/utils/jwt-utils.ts+++ b/nodejs/src/cdp/utils/jwt-utils.ts@@ -7,6 +7,8 @@ export enum PosthogJwtAudience {WORKFLOWS_CANCEL_INVOCATIONS = 'posthog:workflows:cancel_invocations',WORKFLOWS_CANCEL_BATCH = 'posthog:workflows:cancel_batch',TASKS_CREATE = 'posthog:tasks:create',+ // Must match PosthogJwtAudience.CONVERSATIONS_TICKETS in posthog/jwt.py exactly.+ CONVERSATIONS_TICKETS = 'posthog:conversations:tickets',}export class JWT {diff --git a/nodejs/tests/fixtures/hog-bytecode/cd922efc3a14b2467781cc1e62124513bcd4dc311c830be76c0fcaf0db2cbbd3.json b/nodejs/tests/fixtures/hog-bytecode/cd922efc3a14b2467781cc1e62124513bcd4dc311c830be76c0fcaf0db2cbbd3.jsonnew file mode 100644index 000000000000..ef8ebff3e7ad--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/cd922efc3a14b2467781cc1e62124513bcd4dc311c830be76c0fcaf0db2cbbd3.json@@ -0,0 +1 @@+["_H",1,32,"ticket_id",32,"0198a5c1-2f6e-7c3a-9b41-b6d21c0aa111",42,1,2,"postHogGetTicket",1,32,"ticket_id",32,"0198a5c1-2f6e-7c3a-9b41-b6d21c0aa111",42,1,2,"postHogGetTicket",1,36,1,38,35,35]