:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(workflows): explain the missing secret API key instead of naming the field (#79465)
Luke Beltond927bf029843
diff --git a/nodejs/src/cdp/async-functions/conversations.ts b/nodejs/src/cdp/async-functions/conversations.tsindex 4d534bb9be00..16d1d9cf2a41 100644--- a/nodejs/src/cdp/async-functions/conversations.ts+++ b/nodejs/src/cdp/async-functions/conversations.ts@@ -4,6 +4,9 @@ import { CyclotronInvocationQueueParametersFetchSchema } from '~/cdp/schema/cyclimport { HogFlow } from '~/cdp/schema/hogflow'import { registerAsyncFunction } from '../async-function-registry'+import { getTeamWithSecretToken } from './secret-api-token'++const TICKET_ACTIONS = 'ticket workflow actions'registerAsyncFunction('postHogGetTicket', {execute: async (args, context, result) => {@@ -14,13 +17,7 @@ registerAsyncFunction('postHogGetTicket', {throw new Error("[HogFunction] - postHogGetTicket call missing 'ticket_id' property")}- 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) {- throw new Error(`Team ${context.invocation.teamId} has no secret API token configured`)- }+ const team = await getTeamWithSecretToken(context, 'postHogGetTicket', TICKET_ACTIONS)result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({type: 'fetch',@@ -84,13 +81,7 @@ registerAsyncFunction('postHogUpdateTicket', {throw new Error("[HogFunction] - postHogUpdateTicket call missing 'ticket_id' property")}- const updateTeam = await context.teamManager.getTeam(context.invocation.teamId)- if (!updateTeam) {- throw new Error(`Team ${context.invocation.teamId} not found`)- }- if (!updateTeam.secret_api_token) {- throw new Error(`Team ${context.invocation.teamId} has no secret API token configured`)- }+ const updateTeam = await getTeamWithSecretToken(context, 'postHogUpdateTicket', TICKET_ACTIONS)const headers: Record<string, string> = {'Content-Type': 'application/json',diff --git a/nodejs/src/cdp/async-functions/customer_analytics.ts b/nodejs/src/cdp/async-functions/customer_analytics.tsindex 806183d3d038..c6504be87dae 100644--- a/nodejs/src/cdp/async-functions/customer_analytics.ts+++ b/nodejs/src/cdp/async-functions/customer_analytics.ts@@ -2,29 +2,11 @@ import { DateTime } from 'luxon'import { CyclotronInvocationQueueParametersFetchSchema } from '~/cdp/schema/cyclotron'import { HogFlow } from '~/cdp/schema/hogflow'-import { captureException } from '~/common/utils/posthog'-import { Team } from '~/types'--import { AsyncFunctionContext, registerAsyncFunction } from '../async-function-registry'--async function getTeamWithSecretToken(context: AsyncFunctionContext, functionName: 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) {- const error = new Error(`Team ${context.invocation.teamId} has no secret API token configured`)- captureException(error, {- tags: {- team_id: context.invocation.teamId,- function: functionName,- template_id: context.invocation.hogFunction.template_id ?? null,- },- })- throw error- }- return team-}++import { registerAsyncFunction } from '../async-function-registry'+import { getTeamWithSecretToken } from './secret-api-token'++const ACCOUNT_ACTIONS = 'account workflow actions'registerAsyncFunction('postHogGetAccount', {execute: async (args, context, result) => {@@ -35,7 +17,7 @@ registerAsyncFunction('postHogGetAccount', {throw new Error("[HogFunction] - postHogGetAccount call missing 'external_id' property")}- const team = await getTeamWithSecretToken(context, 'postHogGetAccount')+ const team = await getTeamWithSecretToken(context, 'postHogGetAccount', ACCOUNT_ACTIONS)result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({type: 'fetch',@@ -95,7 +77,7 @@ registerAsyncFunction('postHogUpdateAccount', {throw new Error("[HogFunction] - postHogUpdateAccount call missing 'external_id' property")}- const team = await getTeamWithSecretToken(context, 'postHogUpdateAccount')+ const team = await getTeamWithSecretToken(context, 'postHogUpdateAccount', ACCOUNT_ACTIONS)const headers: Record<string, string> = {'Content-Type': 'application/json',@@ -145,7 +127,7 @@ registerAsyncFunction('postHogSetAccountProperties', {throw new Error("[HogFunction] - postHogSetAccountProperties call missing 'external_id' property")}- const team = await getTeamWithSecretToken(context, 'postHogSetAccountProperties')+ const team = await getTeamWithSecretToken(context, 'postHogSetAccountProperties', ACCOUNT_ACTIONS)const headers: Record<string, string> = {'Content-Type': 'application/json',@@ -194,7 +176,7 @@ registerAsyncFunction('postHogCreateAccount', {throw new Error("[HogFunction] - postHogCreateAccount call missing 'external_id' property")}- const team = await getTeamWithSecretToken(context, 'postHogCreateAccount')+ const team = await getTeamWithSecretToken(context, 'postHogCreateAccount', ACCOUNT_ACTIONS)const headers: Record<string, string> = {'Content-Type': 'application/json',diff --git a/nodejs/src/cdp/async-functions/secret-api-token.ts b/nodejs/src/cdp/async-functions/secret-api-token.tsnew file mode 100644index 000000000000..d8cc034ef25d--- /dev/null+++ b/nodejs/src/cdp/async-functions/secret-api-token.ts@@ -0,0 +1,45 @@+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 b5e34488354a..55eb20693c61 100644--- a/nodejs/src/cdp/services/hog-executor.service.test.ts+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts@@ -697,6 +697,49 @@ describe('Hog Executor', () => {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) => {+ 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 () => {+ 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' }),+ })+ )+ })})describe('postHogGetAccount', () => {@@ -772,7 +815,11 @@ describe('Hog Executor', () => {mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme-1' }])const result = await executor.execute(createAccountInvocation())- expect(result.error).toContain('has no secret API token configured')+ // 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 () => {diff --git a/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-get-ticket.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-get-ticket.template.tsindex 1f299c9105ec..2e3185976648 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-get-ticket.template.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-get-ticket.template.ts@@ -1,5 +1,7 @@import { HogFunctionTemplate } from '~/cdp/types'+import { hogApiErrorMessageFn } from '../../hog-helpers'+export const template: HogFunctionTemplate = {free: true,status: 'hidden',@@ -11,6 +13,8 @@ export const template: HogFunctionTemplate = {category: ['Custom'],code_language: 'hog',code: `+${hogApiErrorMessageFn}+if (empty(inputs.ticket_id)) {throw Error('Ticket ID is required')}@@ -18,7 +22,7 @@ if (empty(inputs.ticket_id)) {let response := postHogGetTicket({'ticket_id': inputs.ticket_id})if (response.status != 200) {- throw Error(f'Failed to fetch ticket: {response.status}')+ throw Error(f'Failed to fetch ticket ({response.status}): {apiErrorMessage(response)}')}return response.bodydiff --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.tsnew file mode 100644index 000000000000..19df10f0e573--- /dev/null+++ b/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-tickets.template.test.ts@@ -0,0 +1,57 @@+import { TemplateTester } from '../../test/test-helpers'+import { template as getTicketTemplate } from './posthog-get-ticket.template'+import { template as updateTicketTemplate } from './posthog-update-ticket.template'++describe('posthog conversations ticket templates', () => {+ const cases = [+ {+ name: 'get ticket',+ template: getTicketTemplate,+ inputs: { ticket_id: 'ticket-1' },+ failurePrefix: 'Failed to fetch ticket (401):',+ },+ {+ name: 'update ticket',+ template: updateTicketTemplate,+ inputs: { ticket_id: 'ticket-1', status: 'new' },+ failurePrefix: 'Failed to update ticket (401):',+ },+ ]++ describe.each(cases)('$name', ({ template, inputs, failurePrefix }) => {+ const tester = new TemplateTester(template)++ beforeEach(async () => {+ await tester.beforeEach()+ })++ 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)++ // 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' },+ })++ 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()++ response = await tester.invokeFetchResponse(response.invocation, {+ status: 200,+ body: { id: 'ticket-1', status: 'new' },+ })++ expect(response.error).toBeUndefined()+ expect(response.finished).toBe(true)+ expect(response.execResult).toEqual({ id: 'ticket-1', status: 'new' })+ })+ })+})diff --git a/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-update-ticket.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-update-ticket.template.tsindex 0db129623356..49a16afb61e4 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-update-ticket.template.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-update-ticket.template.ts@@ -1,5 +1,7 @@import { HogFunctionTemplate } from '~/cdp/types'+import { hogApiErrorMessageFn } from '../../hog-helpers'+export const template: HogFunctionTemplate = {free: true,status: 'hidden',@@ -12,6 +14,8 @@ export const template: HogFunctionTemplate = {category: ['Custom'],code_language: 'hog',code: `+${hogApiErrorMessageFn}+if (empty(inputs.ticket_id)) {throw Error('Ticket ID is required')}@@ -61,7 +65,7 @@ let response := postHogUpdateTicket({})if (response.status >= 400) {- throw Error(f'Failed to update ticket: {response.status}')+ throw Error(f'Failed to update ticket ({response.status}): {apiErrorMessage(response)}')}return response.bodydiff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/api-error.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/api-error.tsdeleted file mode 100644index 4708e453bb80..000000000000--- a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/api-error.ts+++ /dev/null@@ -1,3 +0,0 @@-export const hogApiErrorMessageFn = `fun apiErrorMessage(response) {- return response.body.error ?? response.body.detail ?? response.body-}`diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-create-account.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-create-account.template.tsindex 51edc290da5b..aa5cb404be1a 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-create-account.template.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-create-account.template.ts@@ -1,6 +1,6 @@import { HogFunctionTemplate } from '~/cdp/types'-import { hogApiErrorMessageFn } from './api-error'+import { hogApiErrorMessageFn } from '../../hog-helpers'export const template: HogFunctionTemplate = {free: true,diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-get-account.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-get-account.template.tsindex 40083e784654..b9ae22fd297e 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-get-account.template.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-get-account.template.ts@@ -1,6 +1,6 @@import { HogFunctionTemplate } from '~/cdp/types'-import { hogApiErrorMessageFn } from './api-error'+import { hogApiErrorMessageFn } from '../../hog-helpers'export const template: HogFunctionTemplate = {free: true,diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account-property.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account-property.template.tsindex b6c662398384..c961749a195e 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account-property.template.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account-property.template.ts@@ -1,6 +1,6 @@import { HogFunctionTemplate } from '~/cdp/types'-import { hogApiErrorMessageFn } from './api-error'+import { hogApiErrorMessageFn } from '../../hog-helpers'export const template: HogFunctionTemplate = {free: true,diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account.template.tsindex 8c6176b083cb..a9a5de1a1bef 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account.template.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account.template.ts@@ -1,6 +1,6 @@import { HogFunctionTemplate } from '~/cdp/types'-import { hogApiErrorMessageFn } from './api-error'+import { hogApiErrorMessageFn } from '../../hog-helpers'export const template: HogFunctionTemplate = {free: true,diff --git a/nodejs/src/cdp/templates/hog-helpers.ts b/nodejs/src/cdp/templates/hog-helpers.tsnew file mode 100644index 000000000000..b2a95c773815--- /dev/null+++ b/nodejs/src/cdp/templates/hog-helpers.ts@@ -0,0 +1,13 @@+/**+ * Hog snippets shared across templates. Prepended into a template's `code`, so the functions+ * they define are callable from the rest of that template's Hog source.+ */++/**+ * Pulls the human-readable message out of a PostHog API error response, so a failing template+ * surfaces "Invalid API key" rather than a bare status code. Falls back to the whole body for+ * responses that don't use either of our standard error shapes.+ */+export const hogApiErrorMessageFn = `fun apiErrorMessage(response) {+ return response.body.error ?? response.body.detail ?? response.body+}`diff --git a/products/conversations/frontend/scenes/settings/SecretApiKeySection.tsx b/products/conversations/frontend/scenes/settings/SecretApiKeySection.tsxindex 17e3060ee6d9..fd0ae9dccd39 100644--- a/products/conversations/frontend/scenes/settings/SecretApiKeySection.tsx+++ b/products/conversations/frontend/scenes/settings/SecretApiKeySection.tsx@@ -34,7 +34,7 @@ export function SecretApiKeySection(): JSX.Element {<SceneSectiontitle="Secret API key"titleSize="sm"- description="Signs identity hashes for identity verification, and authenticates external API requests for workflows. Project secret API keys can't be used for either."+ description="Authenticates workflow actions that read or update tickets, and signs identity hashes for identity verification. Project secret API keys can't be used for either."><LemonCard hoverEffect={false} className="flex flex-col gap-y-2 max-w-[800px] px-4 py-3"><div>@@ -59,15 +59,21 @@ export function SecretApiKeySection(): JSX.Element {className={currentTeam?.secret_api_token ? '' : 'text-muted'}thing="Secret API key">- {currentTeam?.secret_api_token || 'Click the generate button on the right to create a new key.'}+ {currentTeam?.secret_api_token ||+ 'No key yet — generate one with the button on the right to start using ticket workflow actions.'}</CodeSnippet></div>- {currentTeam?.secret_api_token && (+ {currentTeam?.secret_api_token ? (<LemonBanner type="warning" className="my-2">Rotating this key will require updating it everywhere it's used. Rotate if it has beencompromised or as part of your regular key rotation policy.</LemonBanner>+ ) : (+ <LemonBanner type="warning" className="my-2">+ This project doesn't have a secret API key yet. Workflow steps that get or update tickets will+ fail until you generate one.+ </LemonBanner>)}{currentTeam?.secret_api_token_backup ? (