// @vitest-environment node import { createDbClient, getWriteDbClient } from "@hivegrid/db/client.server"; import { runWithRlsContext } from "@hivegrid/db/rls-context.server"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; /** * This suite must run against the restricted runtime role. Ordinary unit runs * skip it because a mocked client cannot prove FORCE RLS or policy WITH CHECK * behavior. `verify:rls-live` owns the ephemeral database and both URLs. */ const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL; const describeIfDatabase = ADMIN_URL ? describe : describe.skip; const TENANT_A = "chat_system_rls_tenant_a"; const TENANT_B = "chat_system_rls_tenant_b"; const USER_A = "chat_system_rls_user_a"; const USER_B = "chat_system_rls_user_b"; const PIPELINE_A = "chat_system_rls_pipeline_a"; const STAGE_A = "chat_system_rls_stage_a"; const PROJECT_A = "chat_system_rls_project_a"; const GROUP_A = "chat_system_rls_group_a"; const GROUP_B = "chat_system_rls_group_b"; const CHAT_A = "chat_system_rls_project_channel_a"; const MESSAGE_A = "chat_system_rls_message_a"; const GROUP_SOURCE_A = "chat_system_rls_group_source_a"; const CROSS_TENANT_GROUP_SOURCE = "chat_system_rls_cross_tenant_group_source"; describeIfDatabase("chat system ownership with the restricted app role", () => { const admin = createDbClient({ connectionString: ADMIN_URL }); const app = getWriteDbClient(); beforeAll(async () => { await cleanupFixtures(admin); await admin.user.createMany({ data: [ { id: USER_A, email: "chat-system-rls-a@example.test", firstName: "System", lastName: "A", active: true }, { id: USER_B, email: "chat-system-rls-b@example.test", firstName: "System", lastName: "B", active: true }, ], }); await admin.tenant.createMany({ data: [ { id: TENANT_A, slug: TENANT_A, name: "Chat system RLS tenant A", active: true }, { id: TENANT_B, slug: TENANT_B, name: "Chat system RLS tenant B", active: true }, ], }); await admin.tenantUser.createMany({ data: [ { id: "chat_system_rls_tenant_user_a", tenantId: TENANT_A, userId: USER_A, type: 0, joined: 1, status: 2 }, { id: "chat_system_rls_tenant_user_b", tenantId: TENANT_B, userId: USER_B, type: 0, joined: 1, status: 2 }, ], }); await admin.pipeline.create({ data: { id: PIPELINE_A, tenantId: TENANT_A, createdByUserId: USER_A, name: "Chat system RLS pipeline", typHint: "auftrag", }, }); await admin.pipelineStage.create({ data: { id: STAGE_A, tenantId: TENANT_A, pipelineId: PIPELINE_A, name: "Active", stageKind: "offen", }, }); await admin.projekt.create({ data: { id: PROJECT_A, tenantId: TENANT_A, createdByUserId: USER_A, projektNummer: "CHAT-SYSTEM-RLS-001", projektname: "System-created project channel proof", pipelineId: PIPELINE_A, stageId: STAGE_A, }, }); await admin.group.createMany({ data: [ { id: GROUP_A, tenantId: TENANT_A, createdByUserId: USER_A, name: "Same-tenant group", description: "Allowed chat source", color: 1, }, { id: GROUP_B, tenantId: TENANT_B, createdByUserId: USER_B, name: "Foreign-tenant group", description: "Denied chat source", color: 2, }, ], }); }); afterAll(async () => { await cleanupFixtures(admin); await Promise.all([admin.$disconnect(), app.$disconnect()]); }); it("allows actorless project records and rejects a cross-tenant group source through FORCE RLS", async () => { const currentRole = await app.$queryRaw>`SELECT current_user AS "currentUser"`; expect(currentRole).toEqual([{ currentUser: "hivegrid_app" }]); const rlsState = await app.$queryRaw>` SELECT relname AS "tableName", relrowsecurity AS enabled, relforcerowsecurity AS forced FROM pg_catalog.pg_class WHERE relnamespace = 'public'::regnamespace AND relname IN ('TeamChat', 'TeamChatMessage', 'TeamChatGroupSource', 'Group') ORDER BY relname ASC `; expect(rlsState).toHaveLength(4); expect(rlsState.every((table) => table.enabled && table.forced)).toBe(true); // The restricted role sees no tenant rows without a bound identity. await expect(app.teamChat.findMany({ where: { id: CHAT_A }, select: { id: true } })).resolves.toEqual([]); const created = await runWithRlsContext({ tenantId: TENANT_A, userId: USER_A }, () => app.$transaction(async (tx) => { const chat = await tx.teamChat.create({ data: { id: CHAT_A, tenantId: TENANT_A, createdByUserId: null, kind: "project", name: "System project channel", projektId: PROJECT_A, isPrivate: true, eventStreamId: "chat_system_rls_stream_a", }, select: { id: true, tenantId: true, createdByUserId: true, projektId: true }, }); const message = await tx.teamChatMessage.create({ data: { id: MESSAGE_A, tenantId: TENANT_A, chatId: CHAT_A, authorUserId: null, clientMessageId: "system:project-created:chat-system-rls", body: "", bodyFormat: "system", parentMessageId: null, mentions: [], linkPreviews: [], systemEventKey: "project-created:chat-system-rls", systemEventKind: "project_created", systemEventMetadata: { projectId: PROJECT_A, projectName: "System-created project channel proof", }, }, select: { id: true, tenantId: true, authorUserId: true, bodyFormat: true, systemEventKind: true, systemEventMetadata: true, }, }); const groupSource = await tx.teamChatGroupSource.create({ data: { id: GROUP_SOURCE_A, tenantId: TENANT_A, chatId: CHAT_A, groupId: GROUP_A, syncEnabled: true, }, select: { id: true, tenantId: true, chatId: true, groupId: true }, }); return { chat, message, groupSource }; }) ); expect(created.chat).toEqual({ id: CHAT_A, tenantId: TENANT_A, createdByUserId: null, projektId: PROJECT_A }); expect(created.message).toEqual({ id: MESSAGE_A, tenantId: TENANT_A, authorUserId: null, bodyFormat: "system", systemEventKind: "project_created", systemEventMetadata: { projectId: PROJECT_A, projectName: "System-created project channel proof", }, }); expect(created.groupSource).toEqual({ id: GROUP_SOURCE_A, tenantId: TENANT_A, chatId: CHAT_A, groupId: GROUP_A }); await expect( runWithRlsContext({ tenantId: TENANT_A, userId: USER_A }, () => app.teamChatGroupSource.create({ data: { id: CROSS_TENANT_GROUP_SOURCE, tenantId: TENANT_A, chatId: CHAT_A, groupId: GROUP_B, syncEnabled: true, }, }) ) ).rejects.toThrow(); await expect(admin.teamChatGroupSource.count({ where: { id: CROSS_TENANT_GROUP_SOURCE } })).resolves.toBe(0); }); }); async function cleanupFixtures(admin: ReturnType): Promise { await admin.teamChatGroupSource.deleteMany({ where: { id: { in: [GROUP_SOURCE_A, CROSS_TENANT_GROUP_SOURCE] } } }); await admin.teamChatMessage.deleteMany({ where: { id: MESSAGE_A } }); await admin.teamChat.deleteMany({ where: { id: CHAT_A } }); await admin.group.deleteMany({ where: { id: { in: [GROUP_A, GROUP_B] } } }); await admin.projekt.deleteMany({ where: { id: PROJECT_A } }); await admin.pipelineStage.deleteMany({ where: { id: STAGE_A } }); await admin.pipeline.deleteMany({ where: { id: PIPELINE_A } }); await admin.tenantUser.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } }); await admin.tenant.deleteMany({ where: { id: { in: [TENANT_A, TENANT_B] } } }); await admin.user.deleteMany({ where: { id: { in: [USER_A, USER_B] } } }); }