: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(ai-research): drop the organization from the ML key encryption context (#101682)
Robbie6594427a59b7
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.tsindex ed24ccff0d38..0cdf0b4caafa 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts@@ -4,7 +4,7 @@ import {DynamoDBClient,PutItemCommand,} from '@aws-sdk/client-dynamodb'-import { DecryptCommand, GenerateDataKeyCommand, KMSClient } from '@aws-sdk/client-kms'+import { GenerateDataKeyCommand, KMSClient } from '@aws-sdk/client-kms'import { S3Client } from '@aws-sdk/client-s3'import { Message } from 'node-rdkafka'import { register } from 'prom-client'@@ -15,19 +15,27 @@ import { ok } from '~/ingestion/framework/results'import { BlockMetadataBatcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher'import { BlockMetadataParquetStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store'import { toBlockMetadataRow } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-row'+import { MlMirrorMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror/metrics'import { createNoopBlockMetadata } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata'import { MlKeyBatchController } from './batch-controller'-import { MlKeyEncryption } from './crypto'+import { MlDataKey, MlKeyEncryption } from './crypto'import { DynamoItem, MlKeyDynamoDB, encodeKey } from './dynamodb'import { MlSessionKeyStore } from './key-store'import { MlKeyReader } from './reader'-import { MlSessionIdentity, imageKeyId, monthKeyIndexId, sessionKeyId, tableKeyString, teamBlockId } from './schema'+import {+ MlSessionIdentity,+ TableKey,+ imageKeyId,+ monthKeyIndexId,+ sessionKeyId,+ tableKeyString,+ teamBlockId,+} from './schema'import { MlKafkaTransport, mlKafkaRecord } from './transport'const session: MlSessionIdentity = {teamId: 7,- organizationId: 'organization-test',sessionId: '01994569-4380-7000-8000-000000000007',}const table = 'ml-keys-test'@@ -82,12 +90,21 @@ describe('ML session key batches', () => {beforeEach(() => {boundary = new DynamoBoundary()generated = 0+ // Like KMS, a wrapped key only unwraps under the exact encryption context it was wrapped with.+ const wrappedUnder = new Map<string, string>()+ const contextKey = (context?: Record<string, string>): string =>+ JSON.stringify(Object.entries(context ?? {}).sort())kmsSend = jest.fn((command) => {if (command instanceof GenerateDataKeyCommand) {const bytes = Buffer.alloc(32, ++generated)+ wrappedUnder.set(bytes.toString('base64'), contextKey(command.input.EncryptionContext))return Promise.resolve({ Plaintext: bytes, CiphertextBlob: bytes })}- return Promise.resolve({ Plaintext: command.input.CiphertextBlob })+ const wrapped = Buffer.from(command.input.CiphertextBlob)+ if (wrappedUnder.get(wrapped.toString('base64')) !== contextKey(command.input.EncryptionContext)) {+ return Promise.reject(transientError('InvalidCiphertextException'))+ }+ return Promise.resolve({ Plaintext: wrapped })})encryption = new MlKeyEncryption({ send: kmsSend } as unknown as KMSClient,@@ -290,37 +307,93 @@ describe('ML session key batches', () => {expect((await reader.read(locations)).size).toBe(0)})- it('keeps using a key whose row names the organization the team used to belong to', async () => {- const first = await store.prepare([session])- await first.commit()- const location = tableKeyString(sessionKeyId(session.teamId, session.sessionId))- const stored = boundary.items.get(location)!- const moved = { ...session, organizationId: 'organization-new' }- encryption.clear()- const next = await store.prepare([moved])- const keys = next.get(moved.teamId, moved.sessionId)!- expect(keys.session.wrapped).toEqual(Buffer.from(stored.wrapped_key!.B!))- expect(keys.session.identity.organizationId).toBe(session.organizationId)- const unwrap = kmsSend.mock.calls+ it('wraps new keys without an organization and stores none on the row', async () => {+ const batch = await store.prepare([session])+ await batch.commit()+ const generates = kmsSend.mock.calls.map(([command]) => command)- .find((command) => command instanceof DecryptCommand)- expect(unwrap?.input.EncryptionContext?.organization_id).toBe(session.organizationId)- await next.commit()- expect(boundary.items.get(location)).toEqual(stored)+ .filter((c) => c instanceof GenerateDataKeyCommand)+ expect(generates).toHaveLength(2)+ for (const command of generates) {+ expect(command.input.EncryptionContext).not.toHaveProperty('organization_id')+ }+ const stored = boundary.items.get(tableKeyString(sessionKeyId(session.teamId, session.sessionId)))!+ expect(stored).not.toHaveProperty('organization_id')})- it('drops the sessions behind a stored key that has no wrapped key and no tombstone', async () => {- const first = await store.prepare([session])- await first.commit()- const location = tableKeyString(sessionKeyId(session.teamId, session.sessionId))- const { wrapped_key: _wrapped, ...stored } = boundary.items.get(location)!- boundary.items.set(location, stored)+ it('unwraps a key stored under the organization it was wrapped with', async () => {+ const legacyOrganization = 'organization-legacy'+ const sessionKey = await encryption.generate({+ teamId: session.teamId,+ sessionId: session.sessionId,+ organizationId: legacyOrganization,+ })+ const imageKey = await encryption.generate({+ teamId: session.teamId,+ sessionMonth: '2025-09',+ organizationId: legacyOrganization,+ })+ const rows: Array<[TableKey, MlDataKey]> = [+ [sessionKeyId(session.teamId, session.sessionId), sessionKey],+ [imageKeyId(session.teamId, '2025-09'), imageKey],+ ]+ for (const [location, key] of rows) {+ boundary.items.set(tableKeyString(location), {+ ...encodeKey(location),+ wrapped_key: { B: key.wrapped },+ organization_id: { S: legacyOrganization },+ team_id: { N: String(session.teamId) },+ session_month: { S: '2025-09' },+ })+ }+ encryption.clear()const next = await store.prepare([session])- expect(next.get(session.teamId, session.sessionId)).toBeUndefined()+ const keys = next.get(session.teamId, session.sessionId)!+ expect(keys.session.plaintext).toEqual(sessionKey.plaintext)+ expect(keys.image.plaintext).toEqual(imageKey.plaintext)+ expect(keys.session.identity.organizationId).toBe(legacyOrganization)await next.commit()- expect(boundary.items.get(location)).toEqual(stored)+ expect(boundary.writes).toBe(0)+ })++ it('cannot unwrap a stored key under a context it was not wrapped with', async () => {+ const sessionKey = await encryption.generate({+ teamId: session.teamId,+ sessionId: session.sessionId,+ organizationId: 'organization-legacy',+ })+ const location = sessionKeyId(session.teamId, session.sessionId)+ boundary.items.set(tableKeyString(location), {+ ...encodeKey(location),+ wrapped_key: { B: sessionKey.wrapped },+ team_id: { N: String(session.teamId) },+ session_month: { S: '2025-09' },+ })+ encryption.clear()+ await expect(store.prepare([session])).rejects.toThrow('InvalidCiphertextException')})+ it.each([+ ['session', () => sessionKeyId(session.teamId, session.sessionId)],+ ['monthly image', () => imageKeyId(session.teamId, '2025-09')],+ ])(+ 'drops the sessions behind a stored %s key that has no wrapped key and no tombstone, reporting it once',+ async (_kind, keyId) => {+ const first = await store.prepare([session])+ await first.commit()+ const location = tableKeyString(keyId())+ const { wrapped_key: _wrapped, ...stored } = boundary.items.get(location)!+ boundary.items.set(location, stored)+ const unusable = jest.spyOn(MlMirrorMetrics, 'incrementMlKeyIdentityMismatch')+ const next = await store.prepare([session])+ expect(next.get(session.teamId, session.sessionId)).toBeUndefined()+ await next.commit()+ expect(boundary.items.get(location)).toEqual(stored)+ expect(unusable).toHaveBeenCalledTimes(1)+ expect(unusable).toHaveBeenCalledWith('wrapped_key_missing', 1)+ }+ )+it('adopts a competing writer key', async () => {const first = await store.prepare([session])const second = await store.prepare([session])diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.tsindex f9335f5b14d3..009f8ac17eec 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts@@ -60,8 +60,6 @@ export interface MlSessionKeys {interface MlStoredKeyMismatch {id: stringteamId: number- expectedOrganizationId: string- storedOrganizationId?: string}function storedKeyId(identity: MlKeyIdentity): TableKey {@@ -96,6 +94,8 @@ export class MlKeyBatch {private readonly candidates = new Map<string, MlDataKey>()private readonly keys = new Map<string, MlDataKey>()private committed = false+ // persist re-reads the batch after its writes and on every retry, so a row is reported the first time this batch meets it and not on each pass.+ private readonly reportedUnusable = new Set<string>()constructor(private readonly db: MlKeyDynamoDB,@@ -122,7 +122,6 @@ export class MlKeyBatch {for (const sessionId of [identity.sessionId, undefined]) {const keyIdentity = {teamId: identity.teamId,- organizationId: identity.organizationId,...(sessionId ? { sessionId } : { sessionMonth: sessionStartMonth(identity.sessionId) }),}keyIdentities.set(tableKeyString(storedKeyId(keyIdentity)), keyIdentity)@@ -133,7 +132,6 @@ export class MlKeyBatch {this.state.set(id, item)}const unusable: MlStoredKeyMismatch[] = []- const rehomed: MlStoredKeyMismatch[] = []await Promise.all([...keyIdentities].map(async ([id, identity]) => {const item = this.state.get(id)@@ -141,26 +139,16 @@ export class MlKeyBatch {return}if (item) {- const storedOrganizationId = item.organization_id?.S- if (!item.wrapped_key?.B || !storedOrganizationId) {- unusable.push({- id,- teamId: identity.teamId,- expectedOrganizationId: identity.organizationId,- storedOrganizationId,- })+ if (!item.wrapped_key?.B) {+ if (!this.reportedUnusable.has(id)) {+ this.reportedUnusable.add(id)+ unusable.push({ id, teamId: identity.teamId })+ }return}- // The key was wrapped under the organization the row names, and KMS only unwraps it under that same context, so a team that moved organizations keeps its key under the old one.- if (storedOrganizationId !== identity.organizationId) {- rehomed.push({- id,- teamId: identity.teamId,- expectedOrganizationId: identity.organizationId,- storedOrganizationId,- })- }- const storedIdentity = { ...identity, organizationId: storedOrganizationId }+ // A key wrapped while the organization was part of the KMS context only unwraps under that organization, which the row still names.+ const organizationId = item.organization_id?.S+ const storedIdentity = { ...identity, ...(organizationId ? { organizationId } : {}) }this.keys.set(id, await this.encryption.decrypt(storedIdentity, Buffer.from(item.wrapped_key.B)))} else {let candidate = this.candidates.get(id)@@ -172,21 +160,13 @@ export class MlKeyBatch {}}))- if (rehomed.length) {- MlMirrorMetrics.incrementMlKeyIdentityMismatch('organization_changed', rehomed.length)- logger.warn('🔑', 'ml_key_organization_changed', {- count: rehomed.length,- teamIds: [...new Set(rehomed.map((entry) => entry.teamId))].slice(0, 20),- sample: rehomed.slice(0, 5),- })- }// A row with no wrapped key and no tombstone cannot serve this batch; its sessions are dropped like blocked ones so one bad row cannot stop the lane, and the log names it so the data can be repaired.if (unusable.length) {MlMirrorMetrics.incrementMlKeyIdentityMismatch('wrapped_key_missing', unusable.length)logger.error('🔑', 'ml_key_stored_key_unusable', {count: unusable.length,- teamIds: [...new Set(unusable.map((entry) => entry.teamId))].slice(0, 20),- sample: unusable.slice(0, 5),+ teamIds: [...new Set(unusable.map((entry) => entry.teamId))],+ rows: unusable.map((entry) => entry.id),})}}@@ -219,7 +199,6 @@ export class MlKeyBatch {location,{wrapped_key: { B: key.wrapped },- organization_id: { S: key.identity.organizationId },team_id: { N: String(key.identity.teamId) },session_month: { S: keySessionMonth(key.identity) },},diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.tsindex d4cf874e258e..3d9f82527e41 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/reader.ts@@ -16,15 +16,15 @@ export class MlKeyReader {continue}const teamId = Number(item.team_id?.N)- const organizationId = item.organization_id?.S- if (!Number.isSafeInteger(teamId) || !organizationId) {+ if (!Number.isSafeInteger(teamId)) {throw new Error('Invalid ML key record')}const sessionId = item.sk.S?.startsWith('session:') ? item.sk.S.slice('session:'.length) : undefined+ const organizationId = item.organization_id?.Sidentities.set(id, {teamId,- organizationId,...(sessionId ? { sessionId } : { sessionMonth: item.session_month?.S }),+ ...(organizationId ? { organizationId } : {}),})}const state = await this.db.read([...identities.values()].map((identity) => teamBlockId(identity.teamId)))diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema.tsindex 7fdbace621b0..4b5cb3f29dbe 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema.ts@@ -10,15 +10,15 @@ export type MlWireVersion = '1' | '2'export interface MlSessionIdentity {teamId: number- organizationId: stringsessionId: string}export interface MlKeyIdentity {teamId: number- organizationId: stringsessionId?: stringsessionMonth?: string+ /** Only on keys wrapped while the organization was part of the KMS context. A team can change organization mid-session, so new keys leave it out, and a stored key carries the one it was wrapped under. */+ organizationId?: string}export interface TableKey {@@ -69,7 +69,7 @@ export function wrappingContext(identity: MlKeyIdentity): Record<string, string>return {purpose: identity.sessionId ? 'ai-research-session' : 'ai-research-image',team_id: String(identity.teamId),- organization_id: identity.organizationId,+ ...(identity.organizationId ? { organization_id: identity.organizationId } : {}),...(identity.sessionId ? { session_id: identity.sessionId } : {}),...(identity.sessionMonth ? { session_month: identity.sessionMonth } : {}),}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.tsindex 31647d8ce8b9..c27706bcc39f 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts@@ -19,7 +19,7 @@ export type MlUrlCrawlHistoryOutcome = 'fresh' | 'miss' | 'error'export type MlImageSource = 'css' | 'html'/** Phases of the ML key work around one Kafka batch: the key bulk read before processing, the key writes and re-read after it, and the deferred publications. */export type MlKeyPhase = 'prepare' | 'commit' | 'publish'-export type MlKeyIdentityMismatchReason = 'organization_changed' | 'wrapped_key_missing'+export type MlKeyIdentityMismatchReason = 'wrapped_key_missing'export type MlKeyRequest =| 'kms_generate'| 'kms_decrypt'@@ -70,7 +70,7 @@ export class MlMirrorMetrics {})private static readonly mlKeyIdentityMismatch = new Counter({name: 'recording_blob_ingestion_v2_ml_key_identity_mismatch_total',- help: 'Stored ML keys whose row disagrees with the team. organization_changed: the row names another organization than the team has now, and the key is unwrapped under the one the row names (ml_key_organization_changed log). wrapped_key_missing: the row has no wrapped key and no tombstone, and its sessions are dropped (ml_key_stored_key_unusable log)',+ help: 'Stored ML key rows the mirror could not use: the row has no wrapped key and no tombstone, so its sessions are dropped (ml_key_stored_key_unusable log names the rows)',labelNames: ['reason'],})private static readonly mlProducedVersion = new Counter({diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.tsindex f34833508a00..25661d56a3fb 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts@@ -123,16 +123,10 @@ export function createMlMirrorReplayPipeline(.pipeChunk(async function readMlKeyBatch(values) {if (mlOptions.keyManager) {await mlOptions.keyManager.prepare(- values.map((value) => {- if (!value.team.organizationId) {- throw new Error('ML key manager requires organization ownership')- }- return {- teamId: value.team.teamId,- organizationId: value.team.organizationId,- sessionId: value.headers.session_id,- }- })+ values.map((value) => ({+ teamId: value.team.teamId,+ sessionId: value.headers.session_id,+ })))}return values.map((value) => ok(value))diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.mdindex e0f4ca9c1b88..c93f013bf908 100644--- a/products/ai_training/docs/replay-data.md+++ b/products/ai_training/docs/replay-data.md@@ -38,7 +38,8 @@ ML outputs omit distinct IDs, including their hashes and pseudonyms.The metadata consumer projects supported fields before storage, including for messages already in Kafka.A session has one data key.A team has one image key per session start month.-KMS wraps each data key with an encryption context that binds its owner and purpose.+KMS wraps each data key with an encryption context that binds the team, the session or month, and the purpose.+A team can change organization while a session is open, so the organization is not part of that context; keys wrapped before this change carry the organization they were wrapped under on their row, and the mirror unwraps them under it.Payload encryption uses XSalsa20-Poly1305.The authenticated payload also binds the dataset kind and, for images, the object or reference being encrypted.The envelope seals the raw payload with AES-256-GCM.