Skip to content

: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.

fix(cdp): stop persisting destination secrets in invocation errors (#80919)

Daniel Marchuk037a59bd4d22
diff --git a/nodejs/src/cdp/services/hog-executor.service.ts b/nodejs/src/cdp/services/hog-executor.service.ts
index 2e091ecbcad1..99cf467407ed 100644
--- a/nodejs/src/cdp/services/hog-executor.service.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.ts
@@ -13,7 +13,7 @@ import type {
HogFunctionInvocationGlobalsWithInputs,
HogFunctionType,
} from '../types'
-import { createAddLogFunction, sanitizeLogMessage } from '../utils'
+import { createAddLogFunction, getSensitiveValues, redactSensitiveValues, sanitizeLogMessage } from '../utils'
import { execHog } from '../utils/hog-exec'
import { convertToHogFunctionFilterGlobal, filterFunctionInstrumented } from '../utils/hog-function-filtering'
import { createInvocationResult } from '../utils/invocation-utils'
@@ -155,6 +155,10 @@ export class HogExecutorService {
const result = createInvocationResult<CyclotronJobInvocationHogFunction>(invocation, {}, previousResult)
const addLog = createAddLogFunction(result.logs)
+ // Declared out here so the terminal catch can mask secrets out of `result.error`, which is
+ // persisted to `hog_invocation_results.error_message` and rendered in the Invocations tab.
+ let sensitiveValues: string[] = []
+
try {
let globals: HogFunctionInvocationGlobalsWithInputs
let execRes: ExecResult | undefined = undefined
@@ -188,7 +192,7 @@ export class HogExecutorService {
throw e
}
- const sensitiveValues = this.getSensitiveValues(invocation.hogFunction, globals.inputs)
+ sensitiveValues = this.getSensitiveValues(invocation.hogFunction, globals.inputs)
const invocationInput = invocation.state.vmState ?? invocation.hogFunction.bytecode
const eventId = invocation?.state.globals?.event?.uuid || 'Unknown event'
@@ -296,7 +300,10 @@ export class HogExecutorService {
result.execResult = convertHogToJS(execRes.result)
}
} catch (e) {
- addLog('error', `Error executing function on event ${eventId}: ${e}`)
+ addLog(
+ 'error',
+ sanitizeLogMessage([`Error executing function on event ${eventId}: ${e}`], sensitiveValues)
+ )
throw e
}
@@ -348,7 +355,7 @@ export class HogExecutorService {
addLog('debug', messages.join(' '))
}
} catch (err) {
- result.error = err.message
+ result.error = redactSensitiveValues(err.message, sensitiveValues)
result.finished = true // Explicitly set to true to prevent infinite loops
}
@@ -356,45 +363,6 @@ export class HogExecutorService {
}
getSensitiveValues(hogFunction: HogFunctionType, inputs: Record<string, any>): string[] {
- const values: string[] = []
-
- const collectStringValues = (obj: any): void => {
- if (obj && typeof obj === 'object') {
- // Assume the values are the sensitive parts
- Object.values(obj).forEach((val: any) => {
- if (typeof val === 'string') {
- values.push(val)
- }
- })
- }
- }
-
- hogFunction.inputs_schema?.forEach((schema) => {
- if (
- schema.secret ||
- schema.type === 'integration' ||
- schema.type === 'integration_multi' ||
- schema.type === 'push_subscription'
- ) {
- const value = inputs[schema.key]
- if (typeof value === 'string') {
- values.push(value)
- } else if (schema.type === 'integration_multi' && Array.isArray(value)) {
- // integration_multi resolves to an array of integration objects, each carrying its own
- // sensitive_config (e.g. APNs signing_key, FCM access_token_raw) — mask every one.
- value.forEach(collectStringValues)
- } else if (
- (schema.type === 'dictionary' ||
- schema.type === 'integration' ||
- schema.type === 'push_subscription') &&
- typeof value === 'object'
- ) {
- collectStringValues(value)
- }
- }
- })
-
- // We don't want to add "REDACTED" for empty strings
- return values.filter((v) => v.trim())
+ return getSensitiveValues(hogFunction, inputs)
}
}
diff --git a/nodejs/src/cdp/services/native-destination-executor.service.ts b/nodejs/src/cdp/services/native-destination-executor.service.ts
index 190025683c30..ec42918824af 100644
--- a/nodejs/src/cdp/services/native-destination-executor.service.ts
+++ b/nodejs/src/cdp/services/native-destination-executor.service.ts
@@ -7,7 +7,13 @@ import { FetchOptions, FetchResponse } from '~/common/utils/request'
import { NATIVE_HOG_FUNCTIONS_BY_ID } from '../templates'
import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult, Response } from '../types'
import { destinationE2eLagMsSummary } from '../utils'
-import { CDP_TEST_ID, createAddLogFunction, isNativeHogFunction } from '../utils'
+import {
+ CDP_TEST_ID,
+ createAddLogFunction,
+ getSensitiveValues,
+ isNativeHogFunction,
+ redactSensitiveValues,
+} from '../utils'
import { CdpFetchConfig, cdpTrackedFetch, getNextRetryTime, isFetchResponseRetriable } from '../utils/cdp-fetch'
import { createInvocationResult } from '../utils/invocation-utils'
@@ -78,6 +84,7 @@ export class NativeDestinationExecutorService {
// All native plugin options are done as inputs
const config = invocation.state.globals.inputs
+ const sensitiveValues = getSensitiveValues(invocation.hogFunction, config)
if (config.debug_mode) {
addLog('debug', 'config', config)
@@ -177,11 +184,18 @@ export class NativeDestinationExecutorService {
) {
retriesPossible = false
}
+ // Only the copies that get surfaced are masked. The destination's own code
+ // still receives the raw body below, so it can branch on what came back.
+ const reportableResponseText = redactSensitiveValues(
+ fetchResponseText ?? 'unknown',
+ sensitiveValues
+ )
+
addLog(
'warn',
- `HTTP request failed with status ${fetchResponse?.status} (${
- fetchResponseText ?? 'unknown'
- }). ${retriesPossible ? 'Scheduling retry...' : ''}`
+ `HTTP request failed with status ${
+ fetchResponse?.status
+ } (${reportableResponseText}). ${retriesPossible ? 'Scheduling retry...' : ''}`
)
// If it's retriable and we have retries left, we can trigger a retry, otherwise we just pass through to the function
@@ -189,9 +203,7 @@ export class NativeDestinationExecutorService {
throw new FetchError(
`Error executing function on event ${
invocation.state.globals.event.uuid
- }: Request failed with status ${fetchResponse?.status} (${
- fetchResponseText ?? 'unknown'
- })`
+ }: Request failed with status ${fetchResponse?.status} (${reportableResponseText})`
)
}
}
diff --git a/nodejs/src/cdp/services/segment-destination-executor.service.ts b/nodejs/src/cdp/services/segment-destination-executor.service.ts
index 6c5281350521..00823921dcae 100644
--- a/nodejs/src/cdp/services/segment-destination-executor.service.ts
+++ b/nodejs/src/cdp/services/segment-destination-executor.service.ts
@@ -8,7 +8,13 @@ import { LegacyPluginLogger } from '../legacy-plugins/types'
import { SEGMENT_DESTINATIONS_BY_ID } from '../segment/segment-templates'
import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult } from '../types'
import { destinationE2eLagMsSummary } from '../utils'
-import { CDP_TEST_ID, createAddLogFunction, isSegmentPluginHogFunction } from '../utils'
+import {
+ CDP_TEST_ID,
+ createAddLogFunction,
+ getSensitiveValues,
+ isSegmentPluginHogFunction,
+ redactSensitiveValues,
+} from '../utils'
import { CdpFetchConfig, cdpTrackedFetch, getNextRetryTime, isFetchResponseRetriable } from '../utils/cdp-fetch'
import { createInvocationResult } from '../utils/invocation-utils'
@@ -130,6 +136,7 @@ export class SegmentDestinationExecutorService {
// All segment options are done as inputs
const config = invocation.state.globals.inputs
+ const sensitiveValues = getSensitiveValues(invocation.hogFunction, config)
if (config.debug_mode) {
addLog('debug', 'config', config)
@@ -267,11 +274,18 @@ export class SegmentDestinationExecutorService {
) {
retriesPossible = false
}
+ // Only the copies that get surfaced are masked. The destination's own code
+ // still receives the raw body below, so it can branch on what came back.
+ const reportableResponseText = redactSensitiveValues(
+ fetchResponseText ?? 'unknown',
+ sensitiveValues
+ )
+
addLog(
'warn',
- `HTTP request failed with status ${fetchResponse?.status} (${
- fetchResponseText ?? 'unknown'
- }). ${retriesPossible ? 'Scheduling retry...' : ''}`
+ `HTTP request failed with status ${
+ fetchResponse?.status
+ } (${reportableResponseText}). ${retriesPossible ? 'Scheduling retry...' : ''}`
)
// If it's retriable and we have retries left, we can trigger a retry, otherwise we just pass through to the function
@@ -279,9 +293,7 @@ export class SegmentDestinationExecutorService {
throw new SegmentFetchError(
`Error executing function on event ${
invocation.state.globals.event.uuid
- }: Request failed with status ${fetchResponse?.status} (${
- fetchResponseText ?? 'unknown'
- })`
+ }: Request failed with status ${fetchResponse?.status} (${reportableResponseText})`
)
}
}
diff --git a/nodejs/src/cdp/utils.test.ts b/nodejs/src/cdp/utils.test.ts
index f7921b78479e..cb3b07b08696 100644
--- a/nodejs/src/cdp/utils.test.ts
+++ b/nodejs/src/cdp/utils.test.ts
@@ -6,6 +6,7 @@ import { LogEntry } from './types'
import {
convertInternalEventToHogFunctionInvocationGlobals,
fixLogDeduplication,
+ getSensitiveValues,
gzipObject,
sanitizeLogMessage,
unGzipObject,
@@ -124,6 +125,28 @@ describe('Utils', () => {
)
})
})
+ describe('getSensitiveValues', () => {
+ // A webhook's headers input ships as a non-secret dictionary, so nothing in it used to be
+ // masked. That is where the API key of the destination most likely to quote it back lives.
+ const webhookWithHeaders: any = {
+ inputs_schema: [{ key: 'headers', type: 'dictionary', secret: false }],
+ }
+
+ it.each([
+ ['Authorization', 'Bearer sk_live_abc', ['Bearer sk_live_abc', 'sk_live_abc']],
+ ['x-api-key', 'sk_live_abc', ['sk_live_abc']],
+ ])('masks the credential under a non-secret %s header', (header, value, expected) => {
+ expect(getSensitiveValues(webhookWithHeaders, { headers: { [header]: value } })).toEqual(expected)
+ })
+
+ // Redacting these would blank out ordinary headers in every error a destination reports.
+ it('leaves headers that carry no credential alone', () => {
+ expect(getSensitiveValues(webhookWithHeaders, { headers: { 'Content-Type': 'application/json' } })).toEqual(
+ []
+ )
+ })
+ })
+
describe('sanitizeLogMessage', () => {
it('should sanitize the log message', () => {
const message = sanitizeLogMessage(['test', 'test2'])
diff --git a/nodejs/src/cdp/utils.ts b/nodejs/src/cdp/utils.ts
index 104f6f28719d..1fe7b430f0e4 100644
--- a/nodejs/src/cdp/utils.ts
+++ b/nodejs/src/cdp/utils.ts
@@ -294,13 +294,106 @@ export function filterExists<T>(value: T): value is NonNullable<T> {
return Boolean(value)
}
-export const sanitizeLogMessage = (args: any[], sensitiveValues?: string[], maxLength = MAX_LOG_LENGTH): string => {
- let message = args.map((arg) => (typeof arg !== 'string' ? JSON.stringify(arg) : arg)).join(', ')
+// Header names that carry a credential. Matched against the keys of a dictionary input, so a
+// free-form headers map still gets its credential masked without the whole map being treated as
+// secret (which would hide ordinary headers like Content-Type from the person configuring it).
+const CREDENTIAL_HEADER_NAMES =
+ /^(authorization|proxy-authorization|cookie|x-api-key|api-?key|x-auth-token|auth-?token|access-?token|x-auth|token|secret|x-secret)$/i
+
+/**
+ * Every configured secret for a hog function, so callers can mask them out of anything they surface.
+ *
+ * A destination's error text is not safe just because we wrote the format string: it routinely
+ * embeds the third party's response body, and an API that rejects a credential tends to quote the
+ * credential back. Anything built from a response body has to go through `redactSensitiveValues`
+ * with this list before it reaches a log, an error, or ClickHouse.
+ */
+export const getSensitiveValues = (hogFunction: HogFunctionType, inputs: Record<string, any>): string[] => {
+ const values: string[] = []
+
+ const collectStringValues = (obj: any): void => {
+ if (obj && typeof obj === 'object') {
+ // Assume the values are the sensitive parts
+ Object.values(obj).forEach((val: any) => {
+ if (typeof val === 'string') {
+ values.push(val)
+ }
+ })
+ }
+ }
+
+ // A webhook's `headers` is free-form, so it is not marked secret, but it is where a credential
+ // most often sits — and a webhook whose credential is rejected is exactly the case that gets it
+ // quoted back. Mask values under header names that carry one, whatever the secret flag says.
+ const collectCredentialHeaders = (obj: any): void => {
+ if (!obj || typeof obj !== 'object') {
+ return
+ }
+ Object.entries(obj).forEach(([key, val]) => {
+ if (typeof val !== 'string' || !CREDENTIAL_HEADER_NAMES.test(key.trim())) {
+ return
+ }
+ values.push(val)
+ // Sent as "Bearer abc" but usually quoted back as bare "abc", so mask both forms.
+ const withoutScheme = val.replace(/^(bearer|basic|token)\s+/i, '')
+ if (withoutScheme !== val) {
+ values.push(withoutScheme)
+ }
+ })
+ }
+
+ hogFunction.inputs_schema?.forEach((schema) => {
+ if (schema.type === 'dictionary' && !schema.secret) {
+ collectCredentialHeaders(inputs[schema.key])
+ }
+ if (
+ schema.secret ||
+ schema.type === 'integration' ||
+ schema.type === 'integration_multi' ||
+ schema.type === 'push_subscription'
+ ) {
+ const value = inputs[schema.key]
+ if (typeof value === 'string') {
+ values.push(value)
+ } else if (schema.type === 'integration_multi' && Array.isArray(value)) {
+ // integration_multi resolves to an array of integration objects, each carrying its own
+ // sensitive_config (e.g. APNs signing_key, FCM access_token_raw) — mask every one.
+ value.forEach(collectStringValues)
+ } else if (
+ (schema.type === 'dictionary' ||
+ schema.type === 'integration' ||
+ schema.type === 'push_subscription') &&
+ typeof value === 'object'
+ ) {
+ collectStringValues(value)
+ }
+ }
+ })
- // Find and replace any sensitive values
- sensitiveValues?.forEach((sensitiveValue) => {
- message = message.replaceAll(sensitiveValue, '***REDACTED***')
+ // We don't want to add "REDACTED" for empty strings
+ return values.filter((v) => v.trim())
+}
+
+export const redactSensitiveValues = (message: string, sensitiveValues?: string[]): string => {
+ // Callers pass `err.message` straight from a catch, where `err` is `any` and need not be an
+ // Error at all, so a non-string reaches this despite the signature. Hand it back untouched
+ // rather than throwing inside the code path that is reporting someone else's failure.
+ if (!message || typeof message !== 'string' || !sensitiveValues?.length) {
+ return message
+ }
+
+ let redacted = message
+ sensitiveValues.forEach((sensitiveValue) => {
+ redacted = redacted.replaceAll(sensitiveValue, '***REDACTED***')
})
+ return redacted
+}
+
+export const sanitizeLogMessage = (args: any[], sensitiveValues?: string[], maxLength = MAX_LOG_LENGTH): string => {
+ let message = redactSensitiveValues(
+ args.map((arg) => (typeof arg !== 'string' ? JSON.stringify(arg) : arg)).join(', '),
+ sensitiveValues
+ )
let truncateAt = maxLength