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(ingestion): keep transformations off capture-owned $ai_gateway properties (#110568)

Paweł Ledwońfd4175f782a6
diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts
index 4c8fac438fc4..fe08ea4150be 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts
@@ -1007,6 +1007,90 @@ describe('HogTransformer', () => {
expect(result.event?.properties?.success).toBe(true)
expect(result.event?.properties?.should_not_be_set).toBeUndefined()
})
+
+ describe('capture-owned $ai_gateway properties', () => {
+ const insertTransformation = async (hog: string) => {
+ const fn = createHogFunction({
+ type: 'transformation',
+ name: 'gateway writer',
+ team_id: teamId,
+ enabled: true,
+ bytecode: await compileHog(hog),
+ })
+ await insertHogFunction(hub.postgres, teamId, fn)
+ hogTransformer['hogFunctionManager']['onHogFunctionsReloaded'](teamId, [fn.id])
+ }
+
+ it('discards gateway markers a transformation adds', async () => {
+ await insertTransformation(`
+ let returnEvent := event
+ returnEvent.properties['$ai_gateway_verified'] := true
+ returnEvent.properties['$ai_gateway_request_id'] := 'forged'
+ returnEvent.properties['$ai_gateway_relay'] := false
+ returnEvent.properties.touched := true
+ return returnEvent
+ `)
+
+ const event = createPluginEvent(
+ { event: '$ai_generation', properties: { $ai_model: 'claude' } },
+ teamId
+ )
+ const result = await hogTransformer.transformEventAndProduceMessages(event)
+
+ expect(result.event?.properties).toEqual({ $ai_model: 'claude', touched: true })
+ })
+
+ it('restores gateway markers a transformation changes or removes', async () => {
+ await insertTransformation(`
+ let returnEvent := event
+ returnEvent.properties['$ai_gateway_request_id'] := 'forged'
+ returnEvent.properties['$ai_gateway_verified'] := null
+ return returnEvent
+ `)
+
+ const event = createPluginEvent(
+ {
+ event: '$ai_generation',
+ properties: {
+ $ai_model: 'claude',
+ $ai_gateway_verified: true,
+ $ai_gateway_request_id: 'req-1',
+ },
+ },
+ teamId
+ )
+ const result = await hogTransformer.transformEventAndProduceMessages(event)
+
+ expect(result.event?.properties).toEqual({
+ $ai_model: 'claude',
+ $ai_gateway_verified: true,
+ $ai_gateway_request_id: 'req-1',
+ })
+ })
+
+ it('leaves untouched gateway markers alone', async () => {
+ await insertTransformation(`
+ let returnEvent := event
+ returnEvent.properties.touched := true
+ return returnEvent
+ `)
+
+ const event = createPluginEvent(
+ {
+ event: '$ai_generation',
+ properties: { $ai_gateway_verified: true, $ai_gateway_request_id: 'req-1' },
+ },
+ teamId
+ )
+ const result = await hogTransformer.transformEventAndProduceMessages(event)
+
+ expect(result.event?.properties).toEqual({
+ $ai_gateway_verified: true,
+ $ai_gateway_request_id: 'req-1',
+ touched: true,
+ })
+ })
+ })
})
describe('legacy plugins', () => {
diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
index a6d1da04a8d5..b07d00e47a89 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
@@ -7,7 +7,7 @@ import { PostgresRouter } from '~/common/utils/db/postgres'
import { GeoIPService, GeoIp } from '~/common/utils/geoip'
import { logger } from '~/common/utils/logger'
import { PubSub } from '~/common/utils/pubsub'
-import { PluginEvent } from '~/plugin-scaffold'
+import { PluginEvent, Properties } from '~/plugin-scaffold'
import { CyclotronJobInvocationResult, HogFunctionInvocationGlobals, HogFunctionType } from '../../cdp/types'
import { isLegacyPluginHogFunction } from '../../cdp/utils'
@@ -63,6 +63,42 @@ export const hogTransformationUnexpectedErrors = new Counter({
help: 'Number of unexpected errors during transformation execution. Any occurrence should trigger an alert as the transformation is skipped.',
})
+export const hogTransformationProtectedPropertyWrites = new Counter({
+ name: 'hog_transformation_protected_property_writes_total',
+ help: 'Transformations that added, changed or removed a capture-owned $ai_gateway* property. The write is reverted; any occurrence is a billing-exemption forgery attempt worth an alert.',
+})
+
+// Capture stamps these after verifying the AI gateway's signature and the usage report exempts
+// verified events from the AI meter, so transformations must not be able to write them.
+const PROTECTED_PROPERTY_PREFIX = '$ai_gateway'
+
+function pickProtectedProperties(properties: Properties | undefined): Properties {
+ const picked: Properties = {}
+ if (!properties) {
+ return picked
+ }
+ for (const key in properties) {
+ if (key.startsWith(PROTECTED_PROPERTY_PREFIX)) {
+ picked[key] = properties[key]
+ }
+ }
+ return picked
+}
+
+function restoreProtectedProperties(properties: Properties, protectedProperties: Properties): boolean {
+ const written = pickProtectedProperties(properties)
+ for (const key in written) {
+ delete properties[key]
+ }
+ Object.assign(properties, protectedProperties)
+
+ const protectedKeys = Object.keys(protectedProperties)
+ if (Object.keys(written).length !== protectedKeys.length) {
+ return true
+ }
+ return protectedKeys.some((key) => written[key] !== protectedProperties[key])
+}
+
export interface TransformationResult extends HogTransformationResult {
event: PluginEvent | null
invocationResults: CyclotronJobInvocationResult[]
@@ -178,6 +214,7 @@ export class HogTransformerService implements HogTransformer {
}
const results: CyclotronJobInvocationResult[] = []
+ const protectedProperties = pickProtectedProperties(event.properties)
// Create globals once and update the event properties after each transformation
const globals = this.createInvocationGlobals(event)
@@ -299,6 +336,10 @@ export class HogTransformerService implements HogTransformer {
globals.event.distinct_id = event.distinct_id
}
+ if (event.properties && restoreProtectedProperties(event.properties, protectedProperties)) {
+ hogTransformationProtectedPropertyWrites.inc()
+ }
+
return {
event,
invocationResults: results,
diff --git a/nodejs/tests/fixtures/hog-bytecode/0dabea97ca5739d78ffc6748a6697cfd299365e5fabdf7f1d2cdb91564d834e0.json b/nodejs/tests/fixtures/hog-bytecode/0dabea97ca5739d78ffc6748a6697cfd299365e5fabdf7f1d2cdb91564d834e0.json
new file mode 100644
index 000000000000..ade7e45c5a0b
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/0dabea97ca5739d78ffc6748a6697cfd299365e5fabdf7f1d2cdb91564d834e0.json
@@ -0,0 +1 @@
+["_H",1,32,"event",1,1,36,0,32,"properties",45,32,"touched",29,46,36,0,38,35]
diff --git a/nodejs/tests/fixtures/hog-bytecode/88e4eed18b8ec8248a3dc802c056556e23ac05bf6a674326f42f3739ce6e11b3.json b/nodejs/tests/fixtures/hog-bytecode/88e4eed18b8ec8248a3dc802c056556e23ac05bf6a674326f42f3739ce6e11b3.json
new file mode 100644
index 000000000000..9c9c72b516da
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/88e4eed18b8ec8248a3dc802c056556e23ac05bf6a674326f42f3739ce6e11b3.json
@@ -0,0 +1 @@
+["_H",1,32,"event",1,1,36,0,32,"properties",45,32,"$ai_gateway_request_id",32,"forged",46,36,0,32,"properties",45,32,"$ai_gateway_verified",31,46,36,0,38,35]
diff --git a/nodejs/tests/fixtures/hog-bytecode/c2c1c5ab14770f034792a01d8468e9a70907d46b6601cea4ab3e00e9de400afc.json b/nodejs/tests/fixtures/hog-bytecode/c2c1c5ab14770f034792a01d8468e9a70907d46b6601cea4ab3e00e9de400afc.json
new file mode 100644
index 000000000000..d43081527d2a
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/c2c1c5ab14770f034792a01d8468e9a70907d46b6601cea4ab3e00e9de400afc.json
@@ -0,0 +1 @@
+["_H",1,32,"event",1,1,36,0,32,"properties",45,32,"$ai_gateway_verified",29,46,36,0,32,"properties",45,32,"$ai_gateway_request_id",32,"forged",46,36,0,32,"properties",45,32,"$ai_gateway_relay",30,46,36,0,32,"properties",45,32,"touched",29,46,36,0,38,35]