Skip to content

An AI-powered search engine with a generative UI

feat: add performance optimizations for RLS

Yoshiki Miura3b66be06ee61
diff --git a/drizzle/0009_thankful_may_parker.sql b/drizzle/0009_thankful_may_parker.sql
new file mode 100644
index 00000000..a1eb986a
--- /dev/null
+++ b/drizzle/0009_thankful_may_parker.sql
@@ -0,0 +1 @@
+CREATE INDEX "chats_id_user_id_idx" ON "chats" USING btree ("id","user_id");
\ No newline at end of file
diff --git a/drizzle/meta/0008_snapshot.json b/drizzle/meta/0008_snapshot.json
index 8f0efcd3..8ff2fe1f 100644
--- a/drizzle/meta/0008_snapshot.json
+++ b/drizzle/meta/0008_snapshot.json
@@ -102,9 +102,7 @@
"name": "users_manage_own_chats",
"as": "PERMISSIVE",
"for": "ALL",
- "to": [
- "public"
- ],
+ "to": ["public"],
"using": "user_id = current_setting('app.current_user_id', true)",
"withCheck": "user_id = current_setting('app.current_user_id', true)"
},
@@ -112,9 +110,7 @@
"name": "public_chats_readable",
"as": "PERMISSIVE",
"for": "SELECT",
- "to": [
- "public"
- ],
+ "to": ["public"],
"using": "visibility = 'public'"
}
},
@@ -209,9 +205,7 @@
"name": "anyone_can_insert_feedback",
"as": "PERMISSIVE",
"for": "INSERT",
- "to": [
- "public"
- ],
+ "to": ["public"],
"withCheck": "true"
}
},
@@ -303,12 +297,8 @@
"name": "messages_chat_id_chats_id_fk",
"tableFrom": "messages",
"tableTo": "chats",
- "columnsFrom": [
- "chat_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["chat_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -320,9 +310,7 @@
"name": "users_manage_chat_messages",
"as": "PERMISSIVE",
"for": "ALL",
- "to": [
- "public"
- ],
+ "to": ["public"],
"using": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )",
"withCheck": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )"
},
@@ -330,9 +318,7 @@
"name": "public_chat_messages_readable",
"as": "PERMISSIVE",
"for": "SELECT",
- "to": [
- "public"
- ],
+ "to": ["public"],
"using": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".visibility = 'public'\n )"
}
},
@@ -628,12 +614,8 @@
"name": "parts_message_id_messages_id_fk",
"tableFrom": "parts",
"tableTo": "messages",
- "columnsFrom": [
- "message_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -645,9 +627,7 @@
"name": "users_manage_message_parts",
"as": "PERMISSIVE",
"for": "ALL",
- "to": [
- "public"
- ],
+ "to": ["public"],
"using": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )",
"withCheck": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )"
},
@@ -655,9 +635,7 @@
"name": "public_chat_parts_readable",
"as": "PERMISSIVE",
"for": "SELECT",
- "to": [
- "public"
- ],
+ "to": ["public"],
"using": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".visibility = 'public'\n )"
}
},
@@ -697,4 +675,4 @@
"schemas": {},
"tables": {}
}
-}
\ No newline at end of file
+}
diff --git a/drizzle/meta/0009_snapshot.json b/drizzle/meta/0009_snapshot.json
new file mode 100644
index 00000000..df02235a
--- /dev/null
+++ b/drizzle/meta/0009_snapshot.json
@@ -0,0 +1,699 @@
+{
+ "id": "09bf63d0-855c-4ef2-85b7-9f63220f2566",
+ "prevId": "c631d669-f529-4fda-8f77-1db7cc5310e4",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.chats": {
+ "name": "chats",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'private'"
+ }
+ },
+ "indexes": {
+ "chats_user_id_idx": {
+ "name": "chats_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chats_user_id_created_at_idx": {
+ "name": "chats_user_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chats_created_at_idx": {
+ "name": "chats_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chats_id_user_id_idx": {
+ "name": "chats_id_user_id_idx",
+ "columns": [
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_own_chats": {
+ "name": "users_manage_own_chats",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "user_id = current_setting('app.current_user_id', true)",
+ "withCheck": "user_id = current_setting('app.current_user_id', true)"
+ },
+ "public_chats_readable": {
+ "name": "public_chats_readable",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "visibility = 'public'"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.feedback": {
+ "name": "feedback",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sentiment": {
+ "name": "sentiment",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "page_url": {
+ "name": "page_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "feedback_user_id_idx": {
+ "name": "feedback_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "feedback_created_at_idx": {
+ "name": "feedback_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "anyone_can_insert_feedback": {
+ "name": "anyone_can_insert_feedback",
+ "as": "PERMISSIVE",
+ "for": "INSERT",
+ "to": ["public"],
+ "withCheck": "true"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.messages": {
+ "name": "messages",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "messages_chat_id_idx": {
+ "name": "messages_chat_id_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_chat_id_created_at_idx": {
+ "name": "messages_chat_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "messages_chat_id_chats_id_fk": {
+ "name": "messages_chat_id_chats_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "chats",
+ "columnsFrom": ["chat_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_chat_messages": {
+ "name": "users_manage_chat_messages",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )",
+ "withCheck": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )"
+ },
+ "public_chat_messages_readable": {
+ "name": "public_chat_messages_readable",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".visibility = 'public'\n )"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.parts": {
+ "name": "parts",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "order": {
+ "name": "order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "text_text": {
+ "name": "text_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reasoning_text": {
+ "name": "reasoning_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_media_type": {
+ "name": "file_media_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_filename": {
+ "name": "file_filename",
+ "type": "varchar(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_url": {
+ "name": "file_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_url_source_id": {
+ "name": "source_url_source_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_url_url": {
+ "name": "source_url_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_url_title": {
+ "name": "source_url_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_source_id": {
+ "name": "source_document_source_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_media_type": {
+ "name": "source_document_media_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_title": {
+ "name": "source_document_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_filename": {
+ "name": "source_document_filename",
+ "type": "varchar(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_url": {
+ "name": "source_document_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_snippet": {
+ "name": "source_document_snippet",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_tool_call_id": {
+ "name": "tool_tool_call_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_state": {
+ "name": "tool_state",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_error_text": {
+ "name": "tool_error_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_search_input": {
+ "name": "tool_search_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_search_output": {
+ "name": "tool_search_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_fetch_input": {
+ "name": "tool_fetch_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_fetch_output": {
+ "name": "tool_fetch_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_question_input": {
+ "name": "tool_question_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_question_output": {
+ "name": "tool_question_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoWrite_input": {
+ "name": "tool_todoWrite_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoWrite_output": {
+ "name": "tool_todoWrite_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoRead_input": {
+ "name": "tool_todoRead_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoRead_output": {
+ "name": "tool_todoRead_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_input": {
+ "name": "tool_dynamic_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_output": {
+ "name": "tool_dynamic_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_name": {
+ "name": "tool_dynamic_name",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_type": {
+ "name": "tool_dynamic_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data_prefix": {
+ "name": "data_prefix",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data_content": {
+ "name": "data_content",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data_id": {
+ "name": "data_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider_metadata": {
+ "name": "provider_metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "parts_message_id_idx": {
+ "name": "parts_message_id_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "parts_message_id_order_idx": {
+ "name": "parts_message_id_order_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "order",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "parts_message_id_messages_id_fk": {
+ "name": "parts_message_id_messages_id_fk",
+ "tableFrom": "parts",
+ "tableTo": "messages",
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_message_parts": {
+ "name": "users_manage_message_parts",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )",
+ "withCheck": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )"
+ },
+ "public_chat_parts_readable": {
+ "name": "public_chat_parts_readable",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".visibility = 'public'\n )"
+ }
+ },
+ "checkConstraints": {
+ "text_text_required": {
+ "name": "text_text_required",
+ "value": "(type != 'text' OR text_text IS NOT NULL)"
+ },
+ "reasoning_text_required": {
+ "name": "reasoning_text_required",
+ "value": "(type != 'reasoning' OR reasoning_text IS NOT NULL)"
+ },
+ "file_fields_required": {
+ "name": "file_fields_required",
+ "value": "(type != 'file' OR (file_media_type IS NOT NULL AND file_filename IS NOT NULL AND file_url IS NOT NULL))"
+ },
+ "tool_state_valid": {
+ "name": "tool_state_valid",
+ "value": "(tool_state IS NULL OR tool_state IN ('input-streaming', 'input-available', 'output-available', 'output-error'))"
+ },
+ "tool_fields_required": {
+ "name": "tool_fields_required",
+ "value": "(type NOT LIKE 'tool-%' OR (tool_tool_call_id IS NOT NULL AND tool_state IS NOT NULL))"
+ }
+ },
+ "isRLSEnabled": true
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index c9504d51..be20f11d 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -64,6 +64,13 @@
"when": 1755739239041,
"tag": "0008_glamorous_riptide",
"breakpoints": true
+ },
+ {
+ "idx": 9,
+ "version": "7",
+ "when": 1755739927534,
+ "tag": "0009_thankful_may_parker",
+ "breakpoints": true
}
]
-}
\ No newline at end of file
+}
diff --git a/lib/db/__tests__/rls-policies.integration.test.ts b/lib/db/__tests__/rls-policies.integration.test.ts
index 78b49bff..224b3262 100644
--- a/lib/db/__tests__/rls-policies.integration.test.ts
+++ b/lib/db/__tests__/rls-policies.integration.test.ts
@@ -195,10 +195,7 @@ describe('RLS Policies Integration Tests', () => {
const userId = fixtures.users.user1
const chatId = fixtures.chats.privateChat1.id
- const mockUpdateVisibility = vi.spyOn(
- dbActions,
- 'updateChatVisibility'
- )
+ const mockUpdateVisibility = vi.spyOn(dbActions, 'updateChatVisibility')
mockUpdateVisibility.mockImplementation(async (cid, uid, visibility) => {
if (cid === chatId && uid === userId) {
return { ...fixtures.chats.privateChat1, visibility }
@@ -220,10 +217,7 @@ describe('RLS Policies Integration Tests', () => {
const userId = fixtures.users.user1
const chatId = fixtures.chats.privateChat2.id // User 2's chat
- const mockUpdateVisibility = vi.spyOn(
- dbActions,
- 'updateChatVisibility'
- )
+ const mockUpdateVisibility = vi.spyOn(dbActions, 'updateChatVisibility')
mockUpdateVisibility.mockImplementation(async (cid, uid, _visibility) => {
// Simulate RLS blocking update
if (cid === chatId && uid !== fixtures.users.user2) {
@@ -388,4 +382,4 @@ describe('RLS Policies Integration Tests', () => {
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
index 02e7cc0d..6f410302 100644
--- a/lib/db/__tests__/with-rls.test.ts
+++ b/lib/db/__tests__/with-rls.test.ts
@@ -1,12 +1,10 @@
import { sql } from 'drizzle-orm'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { Mock } from 'vitest'
import { db } from '@/lib/db'
-import {
- RLSViolationError,
- withOptionalRLS,
- withRLS
-} from '@/lib/db/with-rls'
+import { RLSViolationError, withOptionalRLS, withRLS } from '@/lib/db/with-rls'
+import type { TxInstance } from '@/lib/db/with-rls'
// Mock the db module
vi.mock('@/lib/db', () => ({
@@ -15,6 +13,14 @@ vi.mock('@/lib/db', () => ({
}
}))
+// Helper to create a minimal mock transaction
+function createMockTx(overrides: Partial<TxInstance> = {}): TxInstance {
+ return {
+ execute: vi.fn(),
+ ...overrides
+ } as unknown as TxInstance
+}
+
describe('RLS Helper Functions', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -24,9 +30,7 @@ describe('RLS Helper Functions', () => {
it('should set user context and execute callback', async () => {
const userId = 'user-123'
const expectedResult = { id: 'result-1' }
- const mockTx = {
- execute: vi.fn()
- }
+ const mockTx = createMockTx()
// Mock the transaction
vi.mocked(db.transaction).mockImplementation(async callback => {
@@ -51,9 +55,7 @@ describe('RLS Helper Functions', () => {
it('should safely handle special characters in userId', async () => {
const userId = "user'; DROP TABLE users; --"
- const mockTx = {
- execute: vi.fn()
- }
+ const mockTx = createMockTx()
vi.mocked(db.transaction).mockImplementation(async callback => {
return callback(mockTx)
@@ -108,19 +110,18 @@ describe('RLS Helper Functions', () => {
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' }])
- })
- }
+ const mockFrom = vi.fn().mockResolvedValue([{ id: 'chat-1' }])
+ const mockSelect = vi.fn().mockReturnValue({ from: mockFrom })
+ const mockTx = createMockTx({
+ select: mockSelect
+ })
vi.mocked(db.transaction).mockImplementation(async callback => {
return callback(mockTx)
})
const result = await withRLS(userId, async tx => {
- return tx.select().from('chats')
+ return tx.select().from('chats' as never)
})
expect(result).toEqual([{ id: 'chat-1' }])
@@ -131,9 +132,7 @@ describe('RLS Helper Functions', () => {
it('should use withRLS when userId is provided', async () => {
const userId = 'user-123'
const expectedResult = { id: 'result-1' }
- const mockTx = {
- execute: vi.fn()
- }
+ const mockTx = createMockTx()
vi.mocked(db.transaction).mockImplementation(async callback => {
return callback(mockTx)
@@ -207,4 +206,4 @@ describe('RLS Helper Functions', () => {
expect(error.stack).toContain('RLSViolationError')
})
})
-})
\ No newline at end of file
+})
diff --git a/lib/db/index.ts b/lib/db/index.ts
index 4f356dba..016ebf7d 100644
--- a/lib/db/index.ts
+++ b/lib/db/index.ts
@@ -1,3 +1,4 @@
+import { sql } from 'drizzle-orm'
import { drizzle } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'
@@ -53,3 +54,40 @@ export const db = drizzle(client, {
// Helper type for all tables
export type Schema = typeof schema
+
+// Verify restricted user permissions on startup
+if (process.env.DATABASE_RESTRICTED_URL && !isTest) {
+ // Only run verification in server environments, not during build
+ if (typeof window === 'undefined' && process.env.NODE_ENV !== 'production') {
+ ;(async () => {
+ try {
+ const result = await db.execute<{ current_user: string }>(
+ sql`SELECT current_user`
+ )
+ const currentUser = result[0]?.current_user
+
+ if (isDevelopment) {
+ console.log('[DB] ✓ Connection verified as user:', currentUser)
+ }
+
+ // Verify it's the restricted user (app_user)
+ if (
+ currentUser &&
+ !currentUser.includes('app_user') &&
+ !currentUser.includes('neondb_owner')
+ ) {
+ console.warn(
+ '[DB] ⚠️ Warning: Expected app_user but connected as:',
+ currentUser
+ )
+ }
+ } catch (error) {
+ console.error('[DB] ✗ Failed to verify database connection:', error)
+ // Don't exit in production, just log the error
+ if (isDevelopment) {
+ process.exit(1)
+ }
+ }
+ })()
+ }
+}
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index fbd43db6..48b851c1 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -47,6 +47,8 @@ export const chats = pgTable(
table.createdAt.desc()
),
index('chats_created_at_idx').on(table.createdAt.desc()),
+ // Composite index for RLS subqueries in messages and parts tables
+ index('chats_id_user_id_idx').on(table.id, table.userId),
// RLS Policies
pgPolicy('users_manage_own_chats', {
diff --git a/lib/db/with-rls.ts b/lib/db/with-rls.ts
index b697bc18..ecd8fdfc 100644
--- a/lib/db/with-rls.ts
+++ b/lib/db/with-rls.ts
@@ -3,8 +3,8 @@ import { sql } from 'drizzle-orm'
import { db } from '.'
// Type for transaction or database instance
-type DbInstance = typeof db
-type TxInstance = Parameters<Parameters<typeof db.transaction>[0]>[0]
+export type DbInstance = typeof db
+export type TxInstance = Parameters<Parameters<typeof db.transaction>[0]>[0]
/**
* Custom error class for RLS violations