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): sign integration access token placeholders (#117691)

Michael Reichenbacha9ae39568634
diff --git a/nodejs/src/cdp/services/hog-executor-async.service.ts b/nodejs/src/cdp/services/hog-executor-async.service.ts
index 89b2a8d07a9b..a59cb6f96fd1 100644
--- a/nodejs/src/cdp/services/hog-executor-async.service.ts
+++ b/nodejs/src/cdp/services/hog-executor-async.service.ts
@@ -1,7 +1,6 @@
import { DateTime } from 'luxon'
import { Counter } from 'prom-client'
-import { ACCESS_TOKEN_PLACEHOLDER } from '~/common/config/constants'
import { instrumented } from '~/common/tracing/tracing-utils'
import { parseJSON } from '~/common/utils/json-parse'
import { logger } from '~/common/utils/logger'
@@ -13,6 +12,7 @@ import '../async-functions'
import type {
CyclotronJobInvocationHogFunction,
CyclotronJobInvocationResult,
+ HogFunctionType,
MinimalAppMetric,
MinimalLogEntry,
} from '../types'
@@ -345,6 +345,20 @@ export class HogExecutorAsyncService {
)
}
+ private async loadIntegrationTokenReplacements(hogFunction: HogFunctionType): Promise<[string, string][]> {
+ const integrationInputs = await this.deps.hogInputsService.loadIntegrationInputs(hogFunction)
+ return Object.values(integrationInputs).flatMap(({ value }): [string, string][] => {
+ // integration_multi inputs resolve to an array of integrations (e.g. push channels)
+ // and do not take part in the single access-token placeholder substitution.
+ if (Array.isArray(value) || !value?.access_token_raw) {
+ return []
+ }
+ return this.deps.hogInputsService
+ .acceptedAccessTokenPlaceholders(value.$integration_id)
+ .map((placeholder) => [placeholder, value.access_token_raw])
+ })
+ }
+
@instrumented('hog-executor.executeFetch')
async executeFetch(
invocation: CyclotronJobInvocationHogFunction,
@@ -373,34 +387,13 @@ export class HogExecutorAsyncService {
headers['developer-token'] = this.config.googleAdwordsDeveloperToken
}
- const integrationInputs = await this.deps.hogInputsService.loadIntegrationInputs(invocation.hogFunction)
-
- if (Object.keys(integrationInputs).length > 0) {
- for (const [key, value] of Object.entries(integrationInputs)) {
- const inputValue = value.value
- // integration_multi inputs resolve to an array of integrations (e.g. push channels)
- // and don't participate in the single access-token placeholder substitution below.
- if (Array.isArray(inputValue) || !inputValue) {
- continue
- }
- const accessToken: string = inputValue.access_token_raw
- if (!accessToken) {
- continue
- }
+ const tokenReplacements = await this.loadIntegrationTokenReplacements(invocation.hogFunction)
+ const replaceTokens = (value: string): string =>
+ tokenReplacements.reduce((acc, [placeholder, token]) => acc.replaceAll(placeholder, token), value)
- const placeholder: string = ACCESS_TOKEN_PLACEHOLDER + invocation.hogFunction.inputs?.[key]?.value
-
- if (placeholder && accessToken) {
- const replace = (val: string) => val.replaceAll(placeholder, accessToken)
-
- params.body = params.body ? replace(params.body) : params.body
- headers = Object.fromEntries(
- Object.entries(params.headers ?? {}).map(([key, value]) => [key, replace(value)])
- )
- params.url = replace(params.url)
- }
- }
- }
+ params.body = params.body ? replaceTokens(params.body) : params.body
+ headers = Object.fromEntries(Object.entries(headers).map(([key, value]) => [key, replaceTokens(value)]))
+ params.url = replaceTokens(params.url)
// Bound event-forwarding loops: a fetch back into this project's own ingestion
// endpoint re-enters the pipeline and can re-trigger this same function. The
diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.ts
index 8fdb14ac10ef..2ae11dcd4a1e 100644
--- a/nodejs/src/cdp/services/hog-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts
@@ -8,7 +8,9 @@ import { DateTime } from 'luxon'
import { AddressInfo } from 'net'
import { CyclotronInvocationQueueParametersFetchType } from '~/cdp/schema/cyclotron'
+import { ACCESS_TOKEN_PLACEHOLDER } from '~/common/config/constants'
import { logger } from '~/common/utils/logger'
+import { createTestTeamFixture } from '~/tests/helpers/sql'
import { HogExecutorAsyncService } from '../../../src/cdp/services/hog-executor-async.service'
import { HogExecutorService } from '../../../src/cdp/services/hog-executor.service'
@@ -29,8 +31,14 @@ import { parseJSON } from '~/common/utils/json-parse'
import { promisifyCallback } from '~/common/utils/utils'
import { compileHog } from '../templates/compiler'
import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../_tests/examples'
-import { createExampleInvocation, createHogExecutionGlobals, createHogFunction } from '../_tests/fixtures'
+import {
+ createExampleInvocation,
+ createHogExecutionGlobals,
+ createHogFunction,
+ insertIntegration,
+} from '../_tests/fixtures'
import { isConnectionLevelError } from '../utils/cdp-fetch'
+import { EncryptedFields } from '../utils/encryption-utils'
import { EXTEND_OBJECT_KEY } from './hog-inputs.service'
import { SELF_LOOP_DEPTH_PROPERTY, selfLoopGuardCounter } from './self-loop-guard'
@@ -59,15 +67,11 @@ describe('Hog Executor', () => {
let executor: HogExecutorAsyncService
let hub: Hub
- beforeEach(async () => {
- const fixedTime = DateTime.fromObject({ year: 2025, month: 1, day: 1 }, { zone: 'UTC' })
- jest.spyOn(Date, 'now').mockReturnValue(fixedTime.toMillis())
-
- hub = await createHub()
+ const createExecutor = (encryptedFields: EncryptedFields): HogExecutorAsyncService => {
const hogInputsService = new HogInputsService(
hub.integrationManager,
new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL),
- hub.encryptedFields
+ encryptedFields
)
const emailService = new EmailService(
{
@@ -87,7 +91,7 @@ describe('Hog Executor', () => {
new RecipientsManagerService(hub.postgres)
)
const recipientTokensService = new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
- executor = new HogExecutorAsyncService(
+ return new HogExecutorAsyncService(
new HogExecutorService({ executionTimeoutMs: hub.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS }, hogInputsService),
{
googleAdwordsDeveloperToken: hub.CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN,
@@ -114,6 +118,14 @@ describe('Hog Executor', () => {
pushNotificationService: undefined as any,
}
)
+ }
+
+ beforeEach(async () => {
+ const fixedTime = DateTime.fromObject({ year: 2025, month: 1, day: 1 }, { zone: 'UTC' })
+ jest.spyOn(Date, 'now').mockReturnValue(fixedTime.toMillis())
+
+ hub = await createHub()
+ executor = createExecutor(hub.encryptedFields)
})
afterEach(async () => {
@@ -2024,7 +2036,10 @@ describe('Hog Executor', () => {
`)
})
- it('replaces access token placeholders in body, headers, and url', async () => {
+ it.each([
+ ['the keys that built the inputs', (keys: string): string => keys],
+ ['a key rotation that promoted a new key', (keys: string): string => `${'n'.repeat(32)},${keys}`],
+ ])('puts each integration token only where the template placed it, under %s', async (_name, rotate) => {
jest.mocked(fetch).mockImplementation(() => {
return Promise.resolve({
status: 200,
@@ -2036,50 +2051,44 @@ describe('Hog Executor', () => {
})
})
- const mockIntegrationInputs = {
- oauth: {
- value: {
- access_token_raw: 'actual_secret_token_12345',
- },
- },
- }
-
- jest.spyOn(executor['deps'].hogInputsService, 'loadIntegrationInputs').mockResolvedValue(
- mockIntegrationInputs
+ const team = (await createTestTeamFixture(hub.postgres)).team
+ const insertTokenIntegration = (token: string) =>
+ insertIntegration(hub.postgres, team.id, {
+ kind: 'oauth',
+ sensitive_config: { access_token: hub.encryptedFields.encrypt(token) },
+ })
+ const crm = await insertTokenIntegration('crm_secret_token')
+ const chat = await insertTokenIntegration('chat_secret_token')
+
+ const invocation = createExampleInvocation({ ...hogFunction, team_id: team.id })
+ invocation.hogFunction.inputs = { crm: { value: crm.id }, chat: { value: chat.id } }
+ invocation.hogFunction.inputs_schema = [
+ { key: 'crm', type: 'integration', required: true },
+ { key: 'chat', type: 'integration', required: true },
+ ]
+ const { inputs } = await executor.hogExecutor.buildInputsWithGlobals(
+ invocation.hogFunction,
+ invocation.state.globals
)
+ const lookAlike = ACCESS_TOKEN_PLACEHOLDER + crm.id
- const invocation = createExampleInvocation()
- invocation.state.globals.inputs = mockIntegrationInputs
- invocation.hogFunction.inputs = {
- oauth: { value: 123 },
- }
invocation.state.vmState = { stack: [] } as any
invocation.queueParameters = {
type: 'fetch',
- url: 'https://example.com/test?q=$$_access_token_placeholder_123',
+ url: `https://example.com/test?q=${inputs.chat.access_token}`,
method: 'POST',
- headers: {
- 'X-Test': '$$_access_token_placeholder_123',
- Authorization: 'Bearer $$_access_token_placeholder_123',
- },
- body: '$$_access_token_placeholder_123',
+ headers: { Authorization: `Bearer ${inputs.crm.access_token}`, 'X-Chat': inputs.chat.access_token },
+ body: JSON.stringify({ token: inputs.crm.access_token, title: lookAlike }),
} as any
- await executor.executeFetch(invocation)
+ await createExecutor(new EncryptedFields(rotate(hub.ENCRYPTION_SALT_KEYS))).executeFetch(invocation)
- expect(jest.mocked(fetch).mock.calls[0] as any).toMatchInlineSnapshot(`
- [
- "https://example.com/test?q=actual_secret_token_12345",
- {
- "body": "actual_secret_token_12345",
- "headers": {
- "Authorization": "Bearer actual_secret_token_12345",
- "X-Test": "actual_secret_token_12345",
- },
- "method": "POST",
- },
- ]
- `)
+ const [url, options] = jest.mocked(fetch).mock.calls[0] as any
+ expect([url, options.headers, parseJSON(options.body)]).toEqual([
+ 'https://example.com/test?q=chat_secret_token',
+ { Authorization: 'Bearer crm_secret_token', 'X-Chat': 'chat_secret_token' },
+ { token: 'crm_secret_token', title: lookAlike },
+ ])
})
describe('with non_failure_status_codes', () => {
diff --git a/nodejs/src/cdp/services/hog-inputs.service.test.ts b/nodejs/src/cdp/services/hog-inputs.service.test.ts
index 6f90e5da7c91..7a098e63e308 100644
--- a/nodejs/src/cdp/services/hog-inputs.service.test.ts
+++ b/nodejs/src/cdp/services/hog-inputs.service.test.ts
@@ -278,18 +278,22 @@ describe('Hog Inputs', () => {
expect(inputs.oauth).toEqual({
$integration_id: integrationId1,
- access_token: `$$_access_token_placeholder_${integrationId1}`,
+ access_token: expect.any(String),
access_token_raw: 'token',
not_encrypted: 'not-encrypted',
team: 'foobar',
})
expect(inputs.auth).toEqual({
$integration_id: integrationId2,
- access_token: `$$_access_token_placeholder_${integrationId2}`,
+ access_token: expect.any(String),
access_token_raw: 'token',
not_encrypted: 'not-encrypted',
team: 'foobar',
})
+ expect(hogInputsService.acceptedAccessTokenPlaceholders(integrationId1)).toContain(
+ inputs.oauth.access_token
+ )
+ expect(hogInputsService.acceptedAccessTokenPlaceholders(integrationId2)).toContain(inputs.auth.access_token)
})
it('should coerce string results to booleans for boolean schema fields', async () => {
diff --git a/nodejs/src/cdp/services/hog-inputs.service.ts b/nodejs/src/cdp/services/hog-inputs.service.ts
index 8d64234da2dc..06f81b7620e1 100644
--- a/nodejs/src/cdp/services/hog-inputs.service.ts
+++ b/nodejs/src/cdp/services/hog-inputs.service.ts
@@ -17,6 +17,12 @@ export const EXTEND_OBJECT_KEY = '$$_extend_object'
const EMAIL_INPUT_TYPES = ['native_email', 'email']
+const ACCESS_TOKEN_PLACEHOLDER_PURPOSE = 'integration-access-token-placeholder'
+
+const accessTokenPlaceholderBase = (integrationId: number): string => `${ACCESS_TOKEN_PLACEHOLDER}${integrationId}`
+
+const signedAccessTokenPlaceholder = (base: string, signature: string): string => `${base}_${signature.slice(0, 32)}`
+
export class HogInputsService {
constructor(
private integrationManager: IntegrationManagerService,
@@ -170,6 +176,20 @@ export class HogInputsService {
return result
}
+ // The fetch step swaps these values for the token wherever they appear in the request, so they must not be
+ // something a request can contain unless the function read it from these inputs.
+ private accessTokenPlaceholder(integrationId: number): string {
+ const base = accessTokenPlaceholderBase(integrationId)
+ return signedAccessTokenPlaceholder(base, this.encryptedFields.sign(ACCESS_TOKEN_PLACEHOLDER_PURPOSE, base))
+ }
+
+ public acceptedAccessTokenPlaceholders(integrationId: number): string[] {
+ const base = accessTokenPlaceholderBase(integrationId)
+ return this.encryptedFields
+ .signatures(ACCESS_TOKEN_PLACEHOLDER_PURPOSE, base)
+ .map((signature) => signedAccessTokenPlaceholder(base, signature))
+ }
+
public async loadIntegrationInputs(
hogFunction: HogFunctionType,
newGlobals?: HogFunctionInvocationGlobalsWithInputs,
@@ -233,7 +253,7 @@ export class HogInputsService {
...integration.sensitive_config,
...(integration.sensitive_config.access_token || integration.config.access_token
? {
- access_token: ACCESS_TOKEN_PLACEHOLDER + integration.id,
+ access_token: this.accessTokenPlaceholder(integration.id),
access_token_raw:
integration.sensitive_config.access_token ?? integration.config.access_token,
}
diff --git a/nodejs/src/cdp/utils/encryption-utils.test.ts b/nodejs/src/cdp/utils/encryption-utils.test.ts
index cad1fa39e99b..5905760085a0 100644
--- a/nodejs/src/cdp/utils/encryption-utils.test.ts
+++ b/nodejs/src/cdp/utils/encryption-utils.test.ts
@@ -10,10 +10,19 @@ describe('Encrypted fields', () => {
encryptedFields = new EncryptedFields(encryptionSaltKeys)
})
- it('should construct with empty keys but throw on encrypt/decrypt', () => {
+ it('should construct with empty keys but throw on encrypt/decrypt/sign', () => {
const empty = new EncryptedFields('')
expect(() => empty.encrypt('test')).toThrow('Encryption keys are not set')
expect(() => empty.decrypt('test')).toThrow('Encryption keys are not set')
+ expect(() => empty.sign('purpose', 'test')).toThrow('Encryption keys are not set')
+ })
+
+ it('signs a value the same way every time, and differently under another key or purpose', () => {
+ const signature = encryptedFields.sign('purpose', 'value')
+
+ expect(encryptedFields.sign('purpose', 'value')).toEqual(signature)
+ expect(new EncryptedFields('f'.repeat(32)).signatures('purpose', 'value')).not.toContain(signature)
+ expect(encryptedFields.signatures('other-purpose', 'value')).not.toContain(signature)
})
describe('encryption and decryption', () => {
@@ -61,11 +70,13 @@ describe('Encrypted fields', () => {
[NEW, OLD],
],
],
- ])('%s: coexisting apps decrypt each others writes', (_name, coexisting) => {
+ ])('%s: coexisting apps decrypt and verify each others writes', (_name, coexisting) => {
for (const writerKeys of coexisting) {
const token = app(writerKeys).encrypt(PLAINTEXT)
+ const signature = app(writerKeys).sign('purpose', PLAINTEXT)
for (const readerKeys of coexisting) {
expect(app(readerKeys).decrypt(token)).toEqual(PLAINTEXT)
+ expect(app(readerKeys).signatures('purpose', PLAINTEXT)).toContain(signature)
}
}
})
diff --git a/nodejs/src/cdp/utils/encryption-utils.ts b/nodejs/src/cdp/utils/encryption-utils.ts
index b107dff18890..9e0d1f6a1d7c 100644
--- a/nodejs/src/cdp/utils/encryption-utils.ts
+++ b/nodejs/src/cdp/utils/encryption-utils.ts
@@ -1,11 +1,29 @@
import { Fernet } from 'fernet-nodejs'
+import { createHmac } from 'node:crypto'
export class EncryptedFields {
private fernets: Fernet[] = []
+ private signingKeys: string[]
constructor(encryptionSaltKeys: string) {
const saltKeys = encryptionSaltKeys.split(',').filter((key) => key)
this.fernets = saltKeys.map((key) => new Fernet(Buffer.from(key, 'utf-8').toString('base64')))
+ this.signingKeys = saltKeys
+ }
+
+ // The purpose keeps a signature made for one use from being valid for another.
+ sign(purpose: string, value: string): string {
+ const [primarySignature] = this.signatures(purpose, value)
+ return primarySignature
+ }
+
+ // One signature per configured key, so that a value signed before a key rotation still verifies.
+ signatures(purpose: string, value: string): string[] {
+ if (!this.signingKeys.length) {
+ throw new Error('Encryption keys are not set')
+ }
+ const message = `${purpose.length}:${purpose}:${value}`
+ return this.signingKeys.map((key) => createHmac('sha256', key).update(message).digest('hex'))
}
encrypt(value: string): string {