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.

8.5 KB
Raw Blame
import {
    ConditionalCheckFailedException,
    DynamoDBClient,
    GetItemCommand,
    PutItemCommand,
    UpdateItemCommand,
} from '@aws-sdk/client-dynamodb'
import { DecryptCommand, GenerateDataKeyCommand, KMSClient } from '@aws-sdk/client-kms'
import sodium from 'libsodium-wrappers'

import { DeleteKeyResult, KeyStore, SessionKey } from '~/ingestion/pipelines/sessionreplay/shared/types'

const KEYS_TABLE_NAME = 'session-recording-keys'
const TOMBSTONE_TTL_SECONDS = 30 * 24 * 60 * 60 // 30 days

/**
 * Keystore backed by DynamoDB and KMS.
 * Used in production cloud environments for secure key management.
 */
export class DynamoDBKeyStore implements KeyStore {
    constructor(
        private dynamoDBClient: DynamoDBClient,
        private kmsClient: KMSClient
    ) {}

    async start(): Promise<void> {
        await sodium.ready
    }

    async generateKey(sessionId: string, teamId: number, retentionDays: number): Promise<SessionKey> {
        const createdAt = Math.floor(Date.now() / 1000)
        const expiresAt = createdAt + retentionDays * 24 * 60 * 60

        const { Plaintext, CiphertextBlob } = await this.kmsClient.send(
            new GenerateDataKeyCommand({
                KeyId: 'alias/session-replay-master-key',
                NumberOfBytes: sodium.crypto_secretbox_KEYBYTES,
                EncryptionContext: {
                    session_id: sessionId,
                    team_id: String(teamId),
                },
            })
        )

        if (!Plaintext || !CiphertextBlob) {
            throw new Error('Failed to generate data key from KMS')
        }

        try {
            await this.dynamoDBClient.send(
                new PutItemCommand({
                    TableName: KEYS_TABLE_NAME,
                    Item: {
                        session_id: { S: sessionId },
                        team_id: { N: String(teamId) },
                        encrypted_key: { B: CiphertextBlob },
                        session_state: { S: 'ciphertext' },
                        created_at: { N: String(createdAt) },
                        expires_at: { N: String(expiresAt) },
                    },
                    ConditionExpression: 'attribute_not_exists(session_id)',
                })
            )
        } catch (error) {
            if (error instanceof ConditionalCheckFailedException) {
                // Key already exists — return the existing key instead of overwriting
                return this.getKey(sessionId, teamId)
            }
            throw error
        }

        return {
            plaintextKey: Buffer.from(Plaintext),
            encryptedKey: Buffer.from(CiphertextBlob),
            sessionState: 'ciphertext',
        }
    }

    async getKey(sessionId: string, teamId: number): Promise<SessionKey> {
        const result = await this.dynamoDBClient.send(
            new GetItemCommand({
                TableName: KEYS_TABLE_NAME,
                Key: {
                    session_id: { S: sessionId },
                    team_id: { N: String(teamId) },
                },
            })
        )

        // Verify the returned item belongs to the requested team (defense in depth)
        if (result.Item?.team_id?.N && parseInt(result.Item.team_id.N, 10) !== teamId) {
            throw new Error(`Team ID mismatch: requested ${teamId}, got ${result.Item.team_id.N}`)
        }

        const sessionState = this.parseSessionState(result.Item)

        if (sessionState === 'ciphertext') {
            if (!result.Item?.encrypted_key?.B) {
                throw new Error(`Missing key data for session ${sessionId} team ${teamId}`)
            }

            const encryptedKey = Buffer.from(result.Item.encrypted_key.B)

            const decryptResult = await this.kmsClient.send(
                new DecryptCommand({
                    CiphertextBlob: encryptedKey,
                    KeyId: 'alias/session-replay-master-key',
                    EncryptionContext: {
                        session_id: sessionId,
                        team_id: String(teamId),
                    },
                })
            )

            if (!decryptResult.Plaintext) {
                throw new Error('Failed to decrypt key from KMS')
            }

            return {
                plaintextKey: Buffer.from(decryptResult.Plaintext),
                encryptedKey,
                sessionState: 'ciphertext',
            }
        } else if (sessionState === 'deleted') {
            if (!result.Item?.deleted_at?.N) {
                throw new Error(`Key for session ${sessionId} is deleted but has no deleted_at timestamp`)
            }
            const deletedAt = parseInt(result.Item.deleted_at.N, 10)
            const deletedBy = result.Item.deleted_by?.S ?? ''
            return {
                plaintextKey: Buffer.alloc(0),
                encryptedKey: Buffer.alloc(0),
                sessionState: 'deleted',
                deletedAt,
                deletedBy,
            }
        } else if (sessionState === 'cleartext') {
            // Recording predates encryption rollout
            return {
                plaintextKey: Buffer.alloc(0),
                encryptedKey: Buffer.alloc(0),
                sessionState: 'cleartext',
            }
        }
        throw new Error(`Unknown session state '${sessionState}' for session ${sessionId} team ${teamId}`)
    }

    private parseSessionState(item: Record<string, any> | undefined): 'ciphertext' | 'cleartext' | 'deleted' {
        if (!item?.session_state?.S) {
            return 'cleartext'
        }
        return item.session_state.S as 'ciphertext' | 'cleartext' | 'deleted'
    }

    async deleteKey(sessionId: string, teamId: number, deletedBy: string): Promise<DeleteKeyResult> {
        const existingItem = await this.dynamoDBClient.send(
            new GetItemCommand({
                TableName: KEYS_TABLE_NAME,
                Key: {
                    session_id: { S: sessionId },
                    team_id: { N: String(teamId) },
                },
            })
        )

        const deletedAt = Math.floor(Date.now() / 1000)

        if (existingItem.Item) {
            // Verify the returned item belongs to the requested team
            if (existingItem.Item.team_id?.N && parseInt(existingItem.Item.team_id.N, 10) !== teamId) {
                throw new Error(`Team ID mismatch: requested ${teamId}, got ${existingItem.Item.team_id.N}`)
            }

            if (existingItem.Item.session_state?.S === 'deleted') {
                if (!existingItem.Item.deleted_at?.N) {
                    throw new Error(`Key for session ${sessionId} is deleted but has no deleted_at timestamp`)
                }
                return {
                    status: 'already_deleted',
                    deletedAt: parseInt(existingItem.Item.deleted_at.N, 10),
                    deletedBy: existingItem.Item.deleted_by?.S ?? '',
                }
            }

            // Shred: atomically remove the encrypted key and mark as deleted
            await this.dynamoDBClient.send(
                new UpdateItemCommand({
                    TableName: KEYS_TABLE_NAME,
                    Key: {
                        session_id: { S: sessionId },
                        team_id: { N: String(teamId) },
                    },
                    UpdateExpression:
                        'SET session_state = :deleted, deleted_at = :deleted_at, deleted_by = :deleted_by REMOVE encrypted_key',
                    ExpressionAttributeValues: {
                        ':deleted': { S: 'deleted' },
                        ':deleted_at': { N: String(deletedAt) },
                        ':deleted_by': { S: deletedBy },
                    },
                })
            )
        } else {
            // Tombstone for cleartext session (predates encryption rollout)
            await this.dynamoDBClient.send(
                new PutItemCommand({
                    TableName: KEYS_TABLE_NAME,
                    Item: {
                        session_id: { S: sessionId },
                        team_id: { N: String(teamId) },
                        session_state: { S: 'deleted' },
                        deleted_at: { N: String(deletedAt) },
                        deleted_by: { S: deletedBy },
                        expires_at: { N: String(deletedAt + TOMBSTONE_TTL_SECONDS) },
                    },
                })
            )
        }

        return { status: 'deleted', deletedAt, deletedBy }
    }

    stop(): void {
        this.kmsClient.destroy()
        this.dynamoDBClient.destroy()
    }
}