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.

16.8 KB
Raw Blame
import { ConditionalCheckFailedException, DynamoDBClient } from '@aws-sdk/client-dynamodb'
import { KMSClient } from '@aws-sdk/client-kms'

import { DynamoDBKeyStore } from './dynamodb-keystore'

describe('DynamoDBKeyStore', () => {
    let keyStore: DynamoDBKeyStore
    let mockDynamoDBClient: jest.Mocked<DynamoDBClient>
    let mockKMSClient: jest.Mocked<KMSClient>

    const mockPlaintextKey = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
    const mockEncryptedKey = new Uint8Array([101, 102, 103, 104, 105])

    describe('create and start', () => {
        it('should create a DynamoDBKeyStore instance and initialize sodium on start', async () => {
            const dynamoDBClient = { send: jest.fn() } as unknown as jest.Mocked<DynamoDBClient>
            const kmsClient = { send: jest.fn() } as unknown as jest.Mocked<KMSClient>

            const store = new DynamoDBKeyStore(dynamoDBClient, kmsClient)
            await store.start()

            expect(store).toBeInstanceOf(DynamoDBKeyStore)
        })
    })

    beforeEach(async () => {
        jest.useFakeTimers()
        jest.setSystemTime(new Date('2024-01-15T12:00:00Z'))

        mockDynamoDBClient = {
            send: jest.fn().mockResolvedValue({}),
        } as unknown as jest.Mocked<DynamoDBClient>

        mockKMSClient = {
            send: jest.fn().mockResolvedValue({
                Plaintext: mockPlaintextKey,
                CiphertextBlob: mockEncryptedKey,
            }),
        } as unknown as jest.Mocked<KMSClient>

        keyStore = new DynamoDBKeyStore(mockDynamoDBClient, mockKMSClient)
        await keyStore.start()
    })

    afterEach(() => {
        jest.useRealTimers()
    })

    describe('generateKey', () => {
        it('should generate a new key and store it in DynamoDB with condition expression', async () => {
            const result = await keyStore.generateKey('session-123', 1, 30)

            expect(mockKMSClient.send).toHaveBeenCalledTimes(1)
            expect(mockDynamoDBClient.send).toHaveBeenCalledTimes(1)

            const dynamoCall = mockDynamoDBClient.send.mock.calls[0][0] as any
            expect(dynamoCall.input.TableName).toBe('session-recording-keys')
            expect(dynamoCall.input.Item.session_id).toEqual({ S: 'session-123' })
            expect(dynamoCall.input.Item.team_id).toEqual({ N: '1' })
            expect(dynamoCall.input.ConditionExpression).toBe('attribute_not_exists(session_id)')

            expect(result.plaintextKey).toEqual(Buffer.from(mockPlaintextKey))
            expect(result.encryptedKey).toEqual(Buffer.from(mockEncryptedKey))
        })

        it('should return existing key when session already has a key in DynamoDB', async () => {
            const existingEncryptedKey = new Uint8Array([201, 202, 203])
            const existingPlaintextKey = new Uint8Array([
                11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
            ])

            ;(mockDynamoDBClient.send as jest.Mock)
                // First call: PutItem fails with ConditionalCheckFailedException
                .mockRejectedValueOnce(
                    new ConditionalCheckFailedException({ message: 'Key already exists', $metadata: {} })
                )
                // Second call: GetItem returns the existing key
                .mockResolvedValueOnce({
                    Item: {
                        session_id: { S: 'session-123' },
                        team_id: { N: '1' },
                        encrypted_key: { B: existingEncryptedKey },
                        session_state: { S: 'ciphertext' },
                    },
                })
            // KMS decrypt for the existing key
            ;(mockKMSClient.send as jest.Mock)
                .mockResolvedValueOnce({ Plaintext: mockPlaintextKey, CiphertextBlob: mockEncryptedKey })
                .mockResolvedValueOnce({ Plaintext: existingPlaintextKey })

            const result = await keyStore.generateKey('session-123', 1, 30)

            expect(result.plaintextKey).toEqual(Buffer.from(existingPlaintextKey))
            expect(result.encryptedKey).toEqual(Buffer.from(existingEncryptedKey))
            expect(result.sessionState).toBe('ciphertext')
        })

        it('should calculate expiration based on the retention days it is given', async () => {
            await keyStore.generateKey('session-123', 1, 90)

            const dynamoCall = mockDynamoDBClient.send.mock.calls[0][0] as any
            const createdAt = Math.floor(new Date('2024-01-15T12:00:00Z').getTime() / 1000)
            const expiresAt = createdAt + 90 * 24 * 60 * 60

            expect(dynamoCall.input.Item.created_at).toEqual({ N: String(createdAt) })
            expect(dynamoCall.input.Item.expires_at).toEqual({ N: String(expiresAt) })
        })

        it('should throw error if KMS fails to generate key', async () => {
            ;(mockKMSClient.send as jest.Mock).mockResolvedValue({
                Plaintext: undefined,
                CiphertextBlob: undefined,
            })

            await expect(keyStore.generateKey('session-123', 1, 30)).rejects.toThrow(
                'Failed to generate data key from KMS'
            )
        })

        it('should throw error if DynamoDB fails to store key', async () => {
            ;(mockDynamoDBClient.send as jest.Mock).mockRejectedValue(new Error('DynamoDB error'))

            await expect(keyStore.generateKey('session-123', 1, 30)).rejects.toThrow('DynamoDB error')
        })
    })

    describe('getKey', () => {
        it('should fetch from DynamoDB and decrypt', async () => {
            ;(mockDynamoDBClient.send as jest.Mock).mockResolvedValue({
                Item: {
                    session_id: { S: 'session-123' },
                    team_id: { N: '1' },
                    encrypted_key: { B: mockEncryptedKey },
                    session_state: { S: 'ciphertext' },
                },
            })
            ;(mockKMSClient.send as jest.Mock).mockResolvedValue({
                Plaintext: mockPlaintextKey,
            })

            const result = await keyStore.getKey('session-123', 1)

            expect(mockDynamoDBClient.send).toHaveBeenCalledTimes(1)
            expect(mockKMSClient.send).toHaveBeenCalledTimes(1)

            expect(result.plaintextKey).toEqual(Buffer.from(mockPlaintextKey))
            expect(result.encryptedKey).toEqual(Buffer.from(mockEncryptedKey))
        })

        it('should return cleartext key if key not found in DynamoDB', async () => {
            ;(mockDynamoDBClient.send as jest.Mock).mockResolvedValue({ Item: undefined })

            const result = await keyStore.getKey('session-123', 1)

            expect(result.plaintextKey).toEqual(Buffer.alloc(0))
            expect(result.encryptedKey).toEqual(Buffer.alloc(0))
            expect(result.sessionState).toBe('cleartext')
        })

        it('should throw error if encrypted_key missing in DynamoDB result for encrypted session', async () => {
            ;(mockDynamoDBClient.send as jest.Mock).mockResolvedValue({
                Item: {
                    session_id: { S: 'session-123' },
                    team_id: { N: '1' },
                    session_state: { S: 'ciphertext' },
                },
            })

            await expect(keyStore.getKey('session-123', 1)).rejects.toThrow(
                'Missing key data for session session-123 team 1'
            )
        })

        it('should return cleartext key if session is not encrypted', async () => {
            ;(mockDynamoDBClient.send as jest.Mock).mockResolvedValue({
                Item: {
                    session_id: { S: 'session-123' },
                    team_id: { N: '1' },
                    session_state: { S: 'cleartext' },
                },
            })

            const result = await keyStore.getKey('session-123', 1)

            expect(result.plaintextKey).toEqual(Buffer.alloc(0))
            expect(result.encryptedKey).toEqual(Buffer.alloc(0))
            expect(result.sessionState).toBe('cleartext')
            expect(mockKMSClient.send).not.toHaveBeenCalled()
        })

        it('should return deleted key with deletedAt if session was deleted', async () => {
            const deletedAt = 1700000000
            ;(mockDynamoDBClient.send as jest.Mock).mockResolvedValue({
                Item: {
                    session_id: { S: 'session-123' },
                    team_id: { N: '1' },
                    session_state: { S: 'deleted' },
                    deleted_at: { N: String(deletedAt) },
                },
            })

            const result = await keyStore.getKey('session-123', 1)

            expect(result.plaintextKey).toEqual(Buffer.alloc(0))
            expect(result.encryptedKey).toEqual(Buffer.alloc(0))
            expect(result.sessionState).toBe('deleted')
            expect(result.deletedAt).toBe(deletedAt)
            expect(mockKMSClient.send).not.toHaveBeenCalled()
        })

        it('should throw if deleted key has no deleted_at timestamp', async () => {
            ;(mockDynamoDBClient.send as jest.Mock).mockResolvedValue({
                Item: {
                    session_id: { S: 'session-123' },
                    team_id: { N: '1' },
                    session_state: { S: 'deleted' },
                },
            })

            await expect(keyStore.getKey('session-123', 1)).rejects.toThrow('no deleted_at timestamp')
        })

        it('should throw error if DynamoDB query fails', async () => {
            ;(mockDynamoDBClient.send as jest.Mock).mockRejectedValue(new Error('DynamoDB network error'))

            await expect(keyStore.getKey('session-123', 1)).rejects.toThrow('DynamoDB network error')
        })

        it('should throw error if KMS fails to decrypt', async () => {
            ;(mockDynamoDBClient.send as jest.Mock).mockResolvedValue({
                Item: {
                    session_id: { S: 'session-123' },
                    team_id: { N: '1' },
                    encrypted_key: { B: mockEncryptedKey },
                    session_state: { S: 'ciphertext' },
                },
            })
            ;(mockKMSClient.send as jest.Mock).mockResolvedValue({
                Plaintext: undefined,
            })

            await expect(keyStore.getKey('session-123', 1)).rejects.toThrow('Failed to decrypt key from KMS')
        })

        it('should throw error if returned team_id does not match requested team_id', async () => {
            ;(mockDynamoDBClient.send as jest.Mock).mockResolvedValue({
                Item: {
                    session_id: { S: 'session-123' },
                    team_id: { N: '999' },
                    session_state: { S: 'cleartext' },
                },
            })

            await expect(keyStore.getKey('session-123', 1)).rejects.toThrow('Team ID mismatch: requested 1, got 999')
        })

        it('should throw error for unknown session state', async () => {
            ;(mockDynamoDBClient.send as jest.Mock).mockResolvedValue({
                Item: {
                    session_id: { S: 'session-123' },
                    team_id: { N: '1' },
                    session_state: { S: 'corrupted' },
                },
            })

            await expect(keyStore.getKey('session-123', 1)).rejects.toThrow(
                "Unknown session state 'corrupted' for session session-123 team 1"
            )
        })
    })

    describe('deleteKey', () => {
        it('should mark key as deleted in DynamoDB and return true if key existed', async () => {
            ;(mockDynamoDBClient.send as jest.Mock)
                .mockResolvedValueOnce({
                    Item: {
                        session_id: { S: 'session-123' },
                        team_id: { N: '1' },
                        session_state: { S: 'ciphertext' },
                    },
                })
                .mockResolvedValueOnce({})

            const result = await keyStore.deleteKey('session-123', 1, '[email protected]')

            expect(mockDynamoDBClient.send).toHaveBeenCalledTimes(2)

            const getCall = mockDynamoDBClient.send.mock.calls[0][0] as any
            expect(getCall.input.TableName).toBe('session-recording-keys')
            expect(getCall.input.Key.session_id).toEqual({ S: 'session-123' })
            expect(getCall.input.Key.team_id).toEqual({ N: '1' })

            const updateCall = mockDynamoDBClient.send.mock.calls[1][0] as any
            expect(updateCall.input.TableName).toBe('session-recording-keys')
            expect(updateCall.input.Key.session_id).toEqual({ S: 'session-123' })
            expect(updateCall.input.Key.team_id).toEqual({ N: '1' })
            expect(updateCall.input.UpdateExpression).toBe(
                'SET session_state = :deleted, deleted_at = :deleted_at, deleted_by = :deleted_by REMOVE encrypted_key'
            )
            expect(result).toEqual({
                status: 'deleted',
                deletedAt: Math.floor(new Date('2024-01-15T12:00:00Z').getTime() / 1000),
                deletedBy: '[email protected]',
            })
        })

        it('should create tombstone if key did not exist', async () => {
            ;(mockDynamoDBClient.send as jest.Mock).mockResolvedValueOnce({ Item: undefined }).mockResolvedValueOnce({})

            const result = await keyStore.deleteKey('session-123', 1, '[email protected]')

            expect(mockDynamoDBClient.send).toHaveBeenCalledTimes(2)

            const putCall = mockDynamoDBClient.send.mock.calls[1][0] as any
            expect(putCall.input.Item.session_state).toEqual({ S: 'deleted' })
            expect(putCall.input.Item.expires_at).toBeDefined()

            const deletedAt = Math.floor(new Date('2024-01-15T12:00:00Z').getTime() / 1000)
            const expiresAt = parseInt(putCall.input.Item.expires_at.N, 10)
            expect(expiresAt).toBe(deletedAt + 30 * 24 * 60 * 60)
            expect(result).toEqual({ status: 'deleted', deletedAt, deletedBy: '[email protected]' })
        })

        it('should return already_deleted with deletedAt if key is already deleted', async () => {
            const deletedAt = 1700000000
            ;(mockDynamoDBClient.send as jest.Mock).mockResolvedValue({
                Item: {
                    session_id: { S: 'session-123' },
                    team_id: { N: '1' },
                    session_state: { S: 'deleted' },
                    deleted_at: { N: String(deletedAt) },
                },
            })

            const result = await keyStore.deleteKey('session-123', 1, '[email protected]')

            expect(result).toEqual({ status: 'already_deleted', deletedAt: 1700000000, deletedBy: '' })
        })

        it('should throw if deleted key has no deleted_at timestamp', async () => {
            ;(mockDynamoDBClient.send as jest.Mock).mockResolvedValue({
                Item: {
                    session_id: { S: 'session-123' },
                    team_id: { N: '1' },
                    session_state: { S: 'deleted' },
                },
            })

            await expect(keyStore.deleteKey('session-123', 1, '[email protected]')).rejects.toThrow(
                'no deleted_at timestamp'
            )
        })

        it('should throw error if DynamoDB get fails', async () => {
            ;(mockDynamoDBClient.send as jest.Mock).mockRejectedValue(new Error('DynamoDB get error'))

            await expect(keyStore.deleteKey('session-123', 1, '[email protected]')).rejects.toThrow('DynamoDB get error')
        })

        it('should throw error if DynamoDB update fails', async () => {
            ;(mockDynamoDBClient.send as jest.Mock)
                .mockResolvedValueOnce({
                    Item: {
                        session_id: { S: 'session-123' },
                        session_state: { S: 'ciphertext' },
                    },
                })
                .mockRejectedValueOnce(new Error('DynamoDB update error'))

            await expect(keyStore.deleteKey('session-123', 1, '[email protected]')).rejects.toThrow(
                'DynamoDB update error'
            )
        })

        it('should throw error if returned team_id does not match requested team_id', async () => {
            ;(mockDynamoDBClient.send as jest.Mock).mockResolvedValue({
                Item: {
                    session_id: { S: 'session-123' },
                    team_id: { N: '999' },
                    session_state: { S: 'ciphertext' },
                },
            })

            await expect(keyStore.deleteKey('session-123', 1, '[email protected]')).rejects.toThrow(
                'Team ID mismatch: requested 1, got 999'
            )
        })
    })

    describe('stop', () => {
        it('should clean up all clients', () => {
            const mockDestroy = jest.fn()
            ;(mockKMSClient as any).destroy = mockDestroy
            ;(mockDynamoDBClient as any).destroy = mockDestroy

            keyStore.stop()

            expect(mockDestroy).toHaveBeenCalledTimes(2)
        })
    })
})