Skip to content

An AI-powered search engine with a generative UI

test: add comprehensive tests for RLS implementation

Yoshiki Miurafa9459120cf5
diff --git a/lib/actions/__tests__/chat.test.ts b/lib/actions/__tests__/chat.test.ts
index c315835d..fded63ea 100644
--- a/lib/actions/__tests__/chat.test.ts
+++ b/lib/actions/__tests__/chat.test.ts
@@ -339,11 +339,14 @@ describe('Chat Actions', () => {
const result = await upsertMessage(chatId, message, userId)
expect(result).toEqual(mockMessage)
- expect(dbActions.upsertMessage).toHaveBeenCalledWith({
- ...message,
- id: 'msg-1',
- chatId
- })
+ expect(dbActions.upsertMessage).toHaveBeenCalledWith(
+ {
+ ...message,
+ id: 'msg-1',
+ chatId
+ },
+ userId
+ )
expect(revalidateTag).toHaveBeenCalledWith(`chat-${chatId}`)
})
@@ -368,11 +371,14 @@ describe('Chat Actions', () => {
await upsertMessage(chatId, message, userId)
- expect(dbActions.upsertMessage).toHaveBeenCalledWith({
- ...message,
- id: expect.any(String),
- chatId
- })
+ expect(dbActions.upsertMessage).toHaveBeenCalledWith(
+ {
+ ...message,
+ id: expect.any(String),
+ chatId
+ },
+ userId
+ )
})
})
diff --git a/lib/db/__tests__/rls-policies.integration.test.ts b/lib/db/__tests__/rls-policies.integration.test.ts
new file mode 100644
index 00000000..78b49bff
--- /dev/null
+++ b/lib/db/__tests__/rls-policies.integration.test.ts
@@ -0,0 +1,391 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import * as dbActions from '@/lib/db/actions'
+import type { Chat } from '@/lib/db/schema'
+import type { UIMessage } from '@/lib/types/ai'
+
+// Mock auth module
+vi.mock('@/lib/auth/get-current-user')
+
+// Test fixtures
+const fixtures = {
+ users: {
+ user1: 'user-123',
+ user2: 'user-456'
+ },
+ chats: {
+ privateChat1: {
+ id: 'private-chat-1',
+ title: 'User 1 Private Chat',
+ userId: 'user-123',
+ visibility: 'private' as const,
+ createdAt: new Date()
+ },
+ privateChat2: {
+ id: 'private-chat-2',
+ title: 'User 2 Private Chat',
+ userId: 'user-456',
+ visibility: 'private' as const,
+ createdAt: new Date()
+ },
+ publicChat: {
+ id: 'public-chat-1',
+ title: 'Public Chat',
+ userId: 'user-123',
+ visibility: 'public' as const,
+ createdAt: new Date()
+ }
+ },
+ messages: {
+ message1: {
+ id: 'msg-1',
+ role: 'user' as const,
+ parts: [{ type: 'text' as const, text: 'Hello from user 1' }]
+ },
+ message2: {
+ id: 'msg-2',
+ role: 'assistant' as const,
+ parts: [{ type: 'text' as const, text: 'Response to user 1' }]
+ }
+ }
+}
+
+describe('RLS Policies Integration Tests', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ describe('Chat Access Control', () => {
+ it('should allow user to access their own private chats', async () => {
+ const userId = fixtures.users.user1
+ const chatId = fixtures.chats.privateChat1.id
+
+ // Mock the database to simulate RLS behavior
+ const mockGetChat = vi.spyOn(dbActions, 'getChat')
+ mockGetChat.mockImplementation(async (id, uid) => {
+ if (id === chatId && uid === userId) {
+ return fixtures.chats.privateChat1
+ }
+ return null
+ })
+
+ const result = await dbActions.getChat(chatId, userId)
+
+ expect(result).toEqual(fixtures.chats.privateChat1)
+ expect(mockGetChat).toHaveBeenCalledWith(chatId, userId)
+ })
+
+ it('should prevent user from accessing other users private chats', async () => {
+ const userId = fixtures.users.user1
+ const chatId = fixtures.chats.privateChat2.id // User 2's chat
+
+ const mockGetChat = vi.spyOn(dbActions, 'getChat')
+ mockGetChat.mockImplementation(async (id, uid) => {
+ // Simulate RLS blocking access
+ if (id === chatId && uid !== fixtures.users.user2) {
+ return null
+ }
+ return fixtures.chats.privateChat2
+ })
+
+ const result = await dbActions.getChat(chatId, userId)
+
+ expect(result).toBeNull()
+ })
+
+ it('should allow anyone to access public chats', async () => {
+ const chatId = fixtures.chats.publicChat.id
+
+ const mockGetChat = vi.spyOn(dbActions, 'getChat')
+ mockGetChat.mockImplementation(async (id, _uid) => {
+ if (id === chatId) {
+ return fixtures.chats.publicChat
+ }
+ return null
+ })
+
+ // Test with authenticated user
+ const result1 = await dbActions.getChat(chatId, fixtures.users.user2)
+ expect(result1).toEqual(fixtures.chats.publicChat)
+
+ // Test without authentication (anonymous)
+ const result2 = await dbActions.getChat(chatId, undefined)
+ expect(result2).toEqual(fixtures.chats.publicChat)
+ })
+
+ it('should only return users own chats in list', async () => {
+ const userId = fixtures.users.user1
+
+ const mockGetChats = vi.spyOn(dbActions, 'getChats')
+ mockGetChats.mockImplementation(async uid => {
+ // Simulate RLS filtering
+ if (uid === userId) {
+ return [fixtures.chats.privateChat1, fixtures.chats.publicChat]
+ }
+ return []
+ })
+
+ const result = await dbActions.getChats(userId)
+
+ expect(result).toHaveLength(2)
+ expect(result).toContainEqual(fixtures.chats.privateChat1)
+ expect(result).toContainEqual(fixtures.chats.publicChat)
+ expect(result).not.toContainEqual(fixtures.chats.privateChat2)
+ })
+ })
+
+ describe('Message Access Control', () => {
+ it('should allow access to messages in users own chats', async () => {
+ const userId = fixtures.users.user1
+ const chatId = fixtures.chats.privateChat1.id
+
+ const mockLoadChat = vi.spyOn(dbActions, 'loadChat')
+ mockLoadChat.mockImplementation(async (cid, uid) => {
+ if (cid === chatId && uid === userId) {
+ return [fixtures.messages.message1, fixtures.messages.message2]
+ }
+ return []
+ })
+
+ const messages = await dbActions.loadChat(chatId, userId)
+
+ expect(messages).toHaveLength(2)
+ expect(messages).toContainEqual(fixtures.messages.message1)
+ })
+
+ it('should allow access to messages in public chats', async () => {
+ const chatId = fixtures.chats.publicChat.id
+
+ const mockLoadChat = vi.spyOn(dbActions, 'loadChat')
+ mockLoadChat.mockImplementation(async cid => {
+ if (cid === chatId) {
+ return [fixtures.messages.message1, fixtures.messages.message2]
+ }
+ return []
+ })
+
+ // Test without authentication
+ const messages = await dbActions.loadChat(chatId, undefined)
+
+ expect(messages).toHaveLength(2)
+ })
+
+ it('should prevent access to messages in other users private chats', async () => {
+ const userId = fixtures.users.user1
+ const chatId = fixtures.chats.privateChat2.id // User 2's chat
+
+ const mockLoadChat = vi.spyOn(dbActions, 'loadChat')
+ mockLoadChat.mockImplementation(async (cid, uid) => {
+ // Simulate RLS blocking access
+ if (cid === chatId && uid !== fixtures.users.user2) {
+ return []
+ }
+ return [fixtures.messages.message1]
+ })
+
+ const messages = await dbActions.loadChat(chatId, userId)
+
+ expect(messages).toHaveLength(0)
+ })
+ })
+
+ describe('Chat Visibility Updates', () => {
+ it('should allow user to update visibility of their own chat', async () => {
+ const userId = fixtures.users.user1
+ const chatId = fixtures.chats.privateChat1.id
+
+ const mockUpdateVisibility = vi.spyOn(
+ dbActions,
+ 'updateChatVisibility'
+ )
+ mockUpdateVisibility.mockImplementation(async (cid, uid, visibility) => {
+ if (cid === chatId && uid === userId) {
+ return { ...fixtures.chats.privateChat1, visibility }
+ }
+ return null
+ })
+
+ const result = await dbActions.updateChatVisibility(
+ chatId,
+ userId,
+ 'public'
+ )
+
+ expect(result).toBeTruthy()
+ expect(result?.visibility).toBe('public')
+ })
+
+ it('should prevent user from updating visibility of other users chat', async () => {
+ const userId = fixtures.users.user1
+ const chatId = fixtures.chats.privateChat2.id // User 2's chat
+
+ const mockUpdateVisibility = vi.spyOn(
+ dbActions,
+ 'updateChatVisibility'
+ )
+ mockUpdateVisibility.mockImplementation(async (cid, uid, _visibility) => {
+ // Simulate RLS blocking update
+ if (cid === chatId && uid !== fixtures.users.user2) {
+ return null
+ }
+ return fixtures.chats.privateChat2
+ })
+
+ const result = await dbActions.updateChatVisibility(
+ chatId,
+ userId,
+ 'public'
+ )
+
+ expect(result).toBeNull()
+ })
+ })
+
+ describe('Chat Creation with RLS', () => {
+ it('should create chat with correct user context', async () => {
+ const userId = fixtures.users.user1
+ const newChat = {
+ id: 'new-chat-1',
+ title: 'New Chat',
+ userId,
+ visibility: 'private' as const
+ }
+
+ const mockCreateChat = vi.spyOn(dbActions, 'createChat')
+ mockCreateChat.mockImplementation(async params => {
+ // Simulate RLS ensuring userId matches
+ if (params.userId === userId) {
+ return { ...newChat, createdAt: new Date() }
+ }
+ throw new Error('RLS violation')
+ })
+
+ const result = await dbActions.createChat(newChat)
+
+ expect(result.userId).toBe(userId)
+ expect(result.title).toBe('New Chat')
+ })
+
+ it('should prevent creating chat with different userId', async () => {
+ const userId = fixtures.users.user1
+ const wrongUserId = fixtures.users.user2
+
+ const mockCreateChat = vi.spyOn(dbActions, 'createChat')
+ mockCreateChat.mockImplementation(async params => {
+ // Simulate RLS checking that userId in data matches context
+ if (params.userId !== userId) {
+ throw new Error('new row violates row-level security policy')
+ }
+ return { ...params, createdAt: new Date() } as Chat
+ })
+
+ // Attempt to create chat with wrong userId should fail
+ await expect(
+ dbActions.createChat({
+ id: 'bad-chat',
+ title: 'Bad Chat',
+ userId: wrongUserId, // Wrong user ID
+ visibility: 'private'
+ })
+ ).rejects.toThrow('row-level security policy')
+ })
+ })
+
+ describe('Message Upsert with RLS', () => {
+ it('should allow upserting messages to users own chat', async () => {
+ const userId = fixtures.users.user1
+ const chatId = fixtures.chats.privateChat1.id
+ const message: UIMessage = {
+ id: 'new-msg-1',
+ role: 'user',
+ parts: [{ type: 'text', text: 'New message' }]
+ }
+
+ const mockUpsertMessage = vi.spyOn(dbActions, 'upsertMessage')
+ mockUpsertMessage.mockImplementation(async (msg, uid) => {
+ // Simulate RLS check
+ if (uid === userId) {
+ return {
+ id: msg.id || 'generated-id',
+ chatId: msg.chatId,
+ role: 'user',
+ metadata: {},
+ createdAt: new Date(),
+ updatedAt: null
+ }
+ }
+ throw new Error('RLS violation')
+ })
+
+ const result = await dbActions.upsertMessage(
+ { ...message, chatId },
+ userId
+ )
+
+ expect(result).toBeTruthy()
+ expect(result.chatId).toBe(chatId)
+ })
+
+ it('should prevent upserting messages to other users chat', async () => {
+ const userId = fixtures.users.user1
+ const chatId = fixtures.chats.privateChat2.id // User 2's chat
+ const message: UIMessage = {
+ id: 'bad-msg-1',
+ role: 'user',
+ parts: [{ type: 'text', text: 'Unauthorized message' }]
+ }
+
+ const mockUpsertMessage = vi.spyOn(dbActions, 'upsertMessage')
+ mockUpsertMessage.mockImplementation(async (_msg, uid) => {
+ // Simulate RLS blocking access to other user's chat
+ if (uid !== fixtures.users.user2) {
+ throw new Error('new row violates row-level security policy')
+ }
+ throw new Error('Should not reach here')
+ })
+
+ await expect(
+ dbActions.upsertMessage({ ...message, chatId }, userId)
+ ).rejects.toThrow('row-level security policy')
+ })
+ })
+
+ describe('Chat Deletion with RLS', () => {
+ it('should allow user to delete their own chat', async () => {
+ const userId = fixtures.users.user1
+ const chatId = fixtures.chats.privateChat1.id
+
+ const mockDeleteChat = vi.spyOn(dbActions, 'deleteChat')
+ mockDeleteChat.mockImplementation(async (cid, uid) => {
+ if (cid === chatId && uid === userId) {
+ return { success: true }
+ }
+ return { success: false, error: 'Unauthorized' }
+ })
+
+ const result = await dbActions.deleteChat(chatId, userId)
+
+ expect(result.success).toBe(true)
+ })
+
+ it('should prevent user from deleting other users chat', async () => {
+ const userId = fixtures.users.user1
+ const chatId = fixtures.chats.privateChat2.id // User 2's chat
+
+ const mockDeleteChat = vi.spyOn(dbActions, 'deleteChat')
+ mockDeleteChat.mockImplementation(async (cid, uid) => {
+ // Simulate RLS blocking deletion
+ if (cid === chatId && uid !== fixtures.users.user2) {
+ return { success: false, error: 'Unauthorized' }
+ }
+ return { success: true }
+ })
+
+ const result = await dbActions.deleteChat(chatId, userId)
+
+ expect(result.success).toBe(false)
+ expect(result.error).toBe('Unauthorized')
+ })
+ })
+})
\ No newline at end of file
diff --git a/lib/db/__tests__/with-rls.test.ts b/lib/db/__tests__/with-rls.test.ts
new file mode 100644
index 00000000..9b428802
--- /dev/null
+++ b/lib/db/__tests__/with-rls.test.ts
@@ -0,0 +1,211 @@
+import { sql } from 'drizzle-orm'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { db } from '@/lib/db'
+import {
+ RLSViolationError,
+ withOptionalRLS,
+ withRLS
+} from '@/lib/db/with-rls'
+
+// Mock the db module
+vi.mock('@/lib/db', () => ({
+ db: {
+ transaction: vi.fn()
+ }
+}))
+
+describe('RLS Helper Functions', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ describe('withRLS', () => {
+ it('should set user context and execute callback', async () => {
+ const userId = 'user-123'
+ const expectedResult = { id: 'result-1' }
+ const mockTx = {
+ execute: vi.fn()
+ }
+
+ // Mock the transaction
+ vi.mocked(db.transaction).mockImplementation(async callback => {
+ return callback(mockTx)
+ })
+
+ const callback = vi.fn().mockResolvedValue(expectedResult)
+
+ const result = await withRLS(userId, callback)
+
+ // Verify SET LOCAL was called with correct user ID
+ expect(mockTx.execute).toHaveBeenCalledWith(
+ sql.raw(`SET LOCAL app.current_user_id = '${userId}'`)
+ )
+
+ // Verify callback was called with transaction
+ expect(callback).toHaveBeenCalledWith(mockTx)
+
+ // Verify result is returned
+ expect(result).toEqual(expectedResult)
+ })
+
+ it('should escape single quotes in userId to prevent SQL injection', async () => {
+ const userId = "user'; DROP TABLE users; --"
+ const escapedUserId = "user''; DROP TABLE users; --"
+ const mockTx = {
+ execute: vi.fn()
+ }
+
+ vi.mocked(db.transaction).mockImplementation(async callback => {
+ return callback(mockTx)
+ })
+
+ await withRLS(userId, async () => {})
+
+ // Verify single quotes are escaped
+ expect(mockTx.execute).toHaveBeenCalledWith(
+ sql.raw(`SET LOCAL app.current_user_id = '${escapedUserId}'`)
+ )
+ })
+
+ it('should throw RLSViolationError for RLS policy violations', async () => {
+ const userId = 'user-123'
+ const rlsError = new Error(
+ 'new row violates row-level security policy for table "chats"'
+ )
+
+ vi.mocked(db.transaction).mockRejectedValue(rlsError)
+
+ await expect(withRLS(userId, async () => {})).rejects.toThrow(
+ RLSViolationError
+ )
+
+ await expect(withRLS(userId, async () => {})).rejects.toThrow(
+ `Access denied for user ${userId}`
+ )
+ })
+
+ it('should re-throw non-RLS errors unchanged', async () => {
+ const userId = 'user-123'
+ const genericError = new Error('Database connection failed')
+
+ vi.mocked(db.transaction).mockRejectedValue(genericError)
+
+ await expect(withRLS(userId, async () => {})).rejects.toThrow(
+ genericError
+ )
+ })
+
+ it('should handle RLS errors without Error instance', async () => {
+ const userId = 'user-123'
+ const rlsErrorString = 'row-level security policy violation'
+
+ vi.mocked(db.transaction).mockRejectedValue(rlsErrorString)
+
+ await expect(withRLS(userId, async () => {})).rejects.toThrow(
+ RLSViolationError
+ )
+ })
+
+ it('should execute callback with transaction result', async () => {
+ const userId = 'user-123'
+ const mockTx = {
+ execute: vi.fn(),
+ select: vi.fn().mockReturnValue({
+ from: vi.fn().mockResolvedValue([{ id: 'chat-1' }])
+ })
+ }
+
+ vi.mocked(db.transaction).mockImplementation(async callback => {
+ return callback(mockTx)
+ })
+
+ const result = await withRLS(userId, async tx => {
+ return tx.select().from('chats')
+ })
+
+ expect(result).toEqual([{ id: 'chat-1' }])
+ })
+ })
+
+ describe('withOptionalRLS', () => {
+ it('should use withRLS when userId is provided', async () => {
+ const userId = 'user-123'
+ const expectedResult = { id: 'result-1' }
+ const mockTx = {
+ execute: vi.fn()
+ }
+
+ vi.mocked(db.transaction).mockImplementation(async callback => {
+ return callback(mockTx)
+ })
+
+ const callback = vi.fn().mockResolvedValue(expectedResult)
+
+ const result = await withOptionalRLS(userId, callback)
+
+ // Verify transaction was used (withRLS path)
+ expect(db.transaction).toHaveBeenCalled()
+ expect(mockTx.execute).toHaveBeenCalledWith(
+ sql.raw(`SET LOCAL app.current_user_id = '${userId}'`)
+ )
+ expect(result).toEqual(expectedResult)
+ })
+
+ it('should use direct db connection when userId is null', async () => {
+ const expectedResult = { id: 'result-1' }
+ const callback = vi.fn().mockResolvedValue(expectedResult)
+
+ const result = await withOptionalRLS(null, callback)
+
+ // Verify transaction was NOT used (direct db path)
+ expect(db.transaction).not.toHaveBeenCalled()
+
+ // Verify callback was called with db directly
+ expect(callback).toHaveBeenCalledWith(db)
+
+ expect(result).toEqual(expectedResult)
+ })
+
+ it('should handle empty string as no userId', async () => {
+ const expectedResult = { id: 'result-1' }
+ const callback = vi.fn().mockResolvedValue(expectedResult)
+
+ const result = await withOptionalRLS('', callback)
+
+ // Empty string should be treated as no userId
+ expect(db.transaction).not.toHaveBeenCalled()
+ expect(callback).toHaveBeenCalledWith(db)
+ expect(result).toEqual(expectedResult)
+ })
+ })
+
+ describe('RLSViolationError', () => {
+ it('should be an instance of Error', () => {
+ const error = new RLSViolationError()
+ expect(error).toBeInstanceOf(Error)
+ })
+
+ it('should have correct name property', () => {
+ const error = new RLSViolationError()
+ expect(error.name).toBe('RLSViolationError')
+ })
+
+ it('should use default message when not provided', () => {
+ const error = new RLSViolationError()
+ expect(error.message).toBe('Row level security policy violation')
+ })
+
+ it('should use custom message when provided', () => {
+ const customMessage = 'Access denied for user 123'
+ const error = new RLSViolationError(customMessage)
+ expect(error.message).toBe(customMessage)
+ })
+
+ it('should maintain stack trace', () => {
+ const error = new RLSViolationError('Test error')
+ expect(error.stack).toBeDefined()
+ expect(error.stack).toContain('RLSViolationError')
+ })
+ })
+})
\ No newline at end of file