Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/chat/src/repository.rls.integration.test.ts
T

916 lines
37 KiB
TypeScript

// @vitest-environment node
import { createDbClient, getWriteDbClient } from "@hivegrid/db/client.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { CHAT_EVENT_NAMES } from "@hivegrid/realtime";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { CHAT_PERMISSIONS } from "./permissions.js";
import { loadChatChannelSettings } from "./channel-settings.server.js";
import { setChatMemberPreferences } from "./member-preferences.server.js";
import {
assertMemberChannelAccess,
authorizeChatGatewayConnection,
fillChatEventGap,
getMemberChannelDetail,
listMemberChannels,
markChatMessageRead,
revalidateChatGatewayAccess,
sendTopLevelChatMessage,
} from "./repository.server.js";
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
const describeIfDatabase = ADMIN_URL ? describe : describe.skip;
const TENANT_A = "chat_repo_rls_tenant_a";
const TENANT_B = "chat_repo_rls_tenant_b";
const MEMBER_A = "chat_repo_rls_member_a";
const OUTSIDER_A = "chat_repo_rls_outsider_a";
const MEMBER_B = "chat_repo_rls_member_b";
const CHAT_A = "chat_repo_rls_channel_a";
const STREAM_A = "chat_repo_rls_stream_a";
const SEARCH_MEMBER_A = "chat_repo_rls_search_member_a";
const PAGE_CHAT_NEWER = "chat_repo_rls_page_channel_newer";
const PAGE_CHAT_OLDER = "chat_repo_rls_page_channel_older";
const PAGE_CHAT_FOREIGN = "chat_repo_rls_page_channel_foreign";
const PAGE_MESSAGE_OLDER = "chat_repo_rls_page_message_older";
const CLIENT_MESSAGE_ID = "chat_repo_rls_client_message_a";
const REQUEST_ID = "chat_repo_rls_request_a";
const GLOBAL_APP_ROLE_ID = "chat_repo_rls_global_app_role";
const GLOBAL_APP_ROLE_NAME = "Chat Repository RLS Global App Role";
const READ_PERMISSION_FIXTURE_ID = "chat_repo_rls_read_permission";
const WRITE_PERMISSION_FIXTURE_ID = "chat_repo_rls_write_permission";
const FILES_READ_PERMISSION_FIXTURE_ID = "chat_repo_rls_files_read_permission";
const FILES_WRITE_PERMISSION_FIXTURE_ID = "chat_repo_rls_files_write_permission";
const MEMBER_A_ROLE_ID = "chat_repo_rls_member_a_role";
const OUTSIDER_A_ROLE_ID = "chat_repo_rls_outsider_a_role";
const MEMBER_B_ROLE_ID = "chat_repo_rls_member_b_role";
const MEMBER_A_SESSION_ID = "chat_repo_rls_member_a_session";
const MEMBER_A_REVOKED_SESSION_ID = "chat_repo_rls_member_a_revoked_session";
const MEMBER_B_SESSION_ID = "chat_repo_rls_member_b_session";
const FILE_A = "chat_repo_rls_file_a";
const FILE_B = "chat_repo_rls_file_b";
const READ_PERMISSIONS = [CHAT_PERMISSIONS.readOwnChannels] as const;
const WRITE_PERMISSIONS = [CHAT_PERMISSIONS.write] as const;
describeIfDatabase("chat repository with the restricted app role", () => {
const admin = createDbClient({ connectionString: ADMIN_URL });
const app = getWriteDbClient();
let readPermissionCreatedByFixture = false;
let writePermissionCreatedByFixture = false;
let filesReadPermissionCreatedByFixture = false;
let filesWritePermissionCreatedByFixture = false;
beforeAll(async () => {
await cleanupFixtures(admin);
await admin.user.createMany({
data: [
{ id: MEMBER_A, email: "chat-repo-member-a@example.test", firstName: "Member", lastName: "A", active: true },
{ id: OUTSIDER_A, email: "chat-repo-outsider-a@example.test", firstName: "Outsider", lastName: "A", active: true },
{ id: MEMBER_B, email: "chat-repo-member-b@example.test", firstName: "Member", lastName: "B", active: true },
],
});
await admin.tenant.createMany({
data: [
{ id: TENANT_A, slug: TENANT_A, name: "Chat repository RLS tenant A", active: true },
{ id: TENANT_B, slug: TENANT_B, name: "Chat repository RLS tenant B", active: true },
],
});
await admin.tenantUser.createMany({
data: [
{ id: "chat_repo_rls_membership_member_a", tenantId: TENANT_A, userId: MEMBER_A, type: 0, joined: 1, status: 2 },
{ id: "chat_repo_rls_membership_outsider_a", tenantId: TENANT_A, userId: OUTSIDER_A, type: 0, joined: 1, status: 2 },
{ id: "chat_repo_rls_membership_member_b", tenantId: TENANT_B, userId: MEMBER_B, type: 0, joined: 1, status: 2 },
],
});
await admin.teamChat.create({
data: {
id: CHAT_A,
tenantId: TENANT_A,
createdByUserId: MEMBER_A,
kind: "group",
name: "Restricted channel A",
isPrivate: true,
eventStreamId: STREAM_A,
},
});
await admin.teamChatMember.create({
data: {
id: "chat_repo_rls_channel_member_a",
tenantId: TENANT_A,
chatId: CHAT_A,
userId: MEMBER_A,
notificationPref: "all_messages",
},
});
await admin.file.createMany({
data: [
{
id: FILE_A,
tenantId: TENANT_A,
createdByUserId: MEMBER_A,
displayName: "voice-note.webm",
mimeType: "audio/webm",
sizeBytes: 12,
storageKey: `tenants/${TENANT_A}/files/${FILE_A}`,
scanStatus: "clean",
previewStatus: "not_supported",
},
{
id: FILE_B,
tenantId: TENANT_B,
createdByUserId: MEMBER_B,
displayName: "foreign.pdf",
mimeType: "application/pdf",
sizeBytes: 20,
storageKey: `tenants/${TENANT_B}/files/${FILE_B}`,
scanStatus: "clean",
previewStatus: "not_supported",
},
],
});
const existingReadPermission = await admin.permission.findUnique({
where: { name: CHAT_PERMISSIONS.readOwnChannels },
select: { id: true },
});
readPermissionCreatedByFixture = existingReadPermission === null || existingReadPermission.id === READ_PERMISSION_FIXTURE_ID;
const readPermission =
existingReadPermission ??
(await admin.permission.create({
data: {
id: READ_PERMISSION_FIXTURE_ID,
name: CHAT_PERMISSIONS.readOwnChannels,
description: "Chat repository restricted-role integration fixture",
type: "app",
isDefault: false,
order: 99_991,
},
select: { id: true },
}));
const existingWritePermission = await admin.permission.findUnique({
where: { name: CHAT_PERMISSIONS.write },
select: { id: true },
});
writePermissionCreatedByFixture = existingWritePermission === null || existingWritePermission.id === WRITE_PERMISSION_FIXTURE_ID;
const writePermission =
existingWritePermission ??
(await admin.permission.create({
data: {
id: WRITE_PERMISSION_FIXTURE_ID,
name: CHAT_PERMISSIONS.write,
description: "Chat repository restricted-role write integration fixture",
type: "app",
isDefault: false,
order: 99_992,
},
select: { id: true },
}));
const existingFilesReadPermission = await admin.permission.findUnique({
where: { name: "files.read_own" },
select: { id: true },
});
filesReadPermissionCreatedByFixture =
existingFilesReadPermission === null || existingFilesReadPermission.id === FILES_READ_PERMISSION_FIXTURE_ID;
const filesReadPermission =
existingFilesReadPermission ??
(await admin.permission.create({
data: {
id: FILES_READ_PERMISSION_FIXTURE_ID,
name: "files.read_own",
description: "Files read permission for the chat restricted-role integration fixture",
type: "app",
isDefault: false,
order: 99_993,
},
select: { id: true },
}));
const existingFilesWritePermission = await admin.permission.findUnique({
where: { name: "files.write" },
select: { id: true },
});
filesWritePermissionCreatedByFixture =
existingFilesWritePermission === null || existingFilesWritePermission.id === FILES_WRITE_PERMISSION_FIXTURE_ID;
const filesWritePermission =
existingFilesWritePermission ??
(await admin.permission.create({
data: {
id: FILES_WRITE_PERMISSION_FIXTURE_ID,
name: "files.write",
description: "Files write permission for the chat restricted-role integration fixture",
type: "app",
isDefault: false,
order: 99_994,
},
select: { id: true },
}));
await admin.role.create({
data: {
id: GLOBAL_APP_ROLE_ID,
tenantId: null,
name: GLOBAL_APP_ROLE_NAME,
description: "Global app role for the chat restricted-role integration proof",
type: "app",
assignToNewUsers: false,
isDefault: false,
order: 99_991,
},
});
await admin.rolePermission.createMany({
data: [
{
id: "chat_repo_rls_global_role_read_permission",
roleId: GLOBAL_APP_ROLE_ID,
permissionId: readPermission.id,
},
{
id: "chat_repo_rls_global_role_write_permission",
roleId: GLOBAL_APP_ROLE_ID,
permissionId: writePermission.id,
},
{
id: "chat_repo_rls_global_role_files_read_permission",
roleId: GLOBAL_APP_ROLE_ID,
permissionId: filesReadPermission.id,
},
{
id: "chat_repo_rls_global_role_files_write_permission",
roleId: GLOBAL_APP_ROLE_ID,
permissionId: filesWritePermission.id,
},
],
});
await admin.userRole.createMany({
data: [
{ id: MEMBER_A_ROLE_ID, tenantId: TENANT_A, userId: MEMBER_A, roleId: GLOBAL_APP_ROLE_ID },
{ id: OUTSIDER_A_ROLE_ID, tenantId: TENANT_A, userId: OUTSIDER_A, roleId: GLOBAL_APP_ROLE_ID },
{ id: MEMBER_B_ROLE_ID, tenantId: TENANT_B, userId: MEMBER_B, roleId: GLOBAL_APP_ROLE_ID },
],
});
const expiresAt = new Date(Date.now() + 60 * 60 * 1_000);
await admin.userSession.createMany({
data: [
{
id: MEMBER_A_SESSION_ID,
userId: MEMBER_A,
tokenHash: "chat_repo_rls_member_a_session_hash",
expiresAt,
},
{
id: MEMBER_A_REVOKED_SESSION_ID,
userId: MEMBER_A,
tokenHash: "chat_repo_rls_member_a_revoked_session_hash",
expiresAt,
revokedAt: new Date(),
},
{
id: MEMBER_B_SESSION_ID,
userId: MEMBER_B,
tokenHash: "chat_repo_rls_member_b_session_hash",
expiresAt,
},
],
});
});
afterAll(async () => {
await cleanupFixtures(admin);
if (readPermissionCreatedByFixture) {
await admin.permission.deleteMany({ where: { id: READ_PERMISSION_FIXTURE_ID, name: CHAT_PERMISSIONS.readOwnChannels } });
}
if (writePermissionCreatedByFixture) {
await admin.permission.deleteMany({ where: { id: WRITE_PERMISSION_FIXTURE_ID, name: CHAT_PERMISSIONS.write } });
}
if (filesReadPermissionCreatedByFixture) {
await admin.permission.deleteMany({ where: { id: FILES_READ_PERMISSION_FIXTURE_ID, name: "files.read_own" } });
}
if (filesWritePermissionCreatedByFixture) {
await admin.permission.deleteMany({ where: { id: FILES_WRITE_PERMISSION_FIXTURE_ID, name: "files.write" } });
}
await Promise.all([admin.$disconnect(), app.$disconnect()]);
});
it("revalidates gateway sessions, global app-role permissions, tenant scope, and live channel membership under FORCE RLS", async () => {
const currentRole = await app.$queryRaw<Array<{ currentUser: string }>>`SELECT current_user AS "currentUser"`;
expect(currentRole).toEqual([{ currentUser: "hivegrid_app" }]);
const rlsState = await app.$queryRaw<Array<{ tableName: string; enabled: boolean; forced: boolean }>>`
SELECT relname AS "tableName", relrowsecurity AS enabled, relforcerowsecurity AS forced
FROM pg_catalog.pg_class
WHERE relnamespace = 'public'::regnamespace
AND relname IN ('TeamChat', 'TeamChatMember', 'UserSession', 'UserRole', 'Role', 'RolePermission')
ORDER BY relname ASC
`;
expect(rlsState).toHaveLength(6);
expect(rlsState.every((table) => table.enabled && table.forced)).toBe(true);
const visibleGatewayPermissions = await runWithRlsContext(
{ tenantId: TENANT_A, userId: MEMBER_A },
() =>
app.$queryRaw<Array<{ name: string; roleTenantId: string | null; assignmentTenantId: string }>>`
SELECT
permission_row."name",
role_row."tenantId" AS "roleTenantId",
user_role."tenantId" AS "assignmentTenantId"
FROM "UserRole" AS user_role
INNER JOIN "Role" AS role_row ON role_row."id" = user_role."roleId"
INNER JOIN "RolePermission" AS role_permission ON role_permission."roleId" = role_row."id"
INNER JOIN "Permission" AS permission_row ON permission_row."id" = role_permission."permissionId"
WHERE user_role."tenantId" = ${TENANT_A}
AND user_role."userId" = ${MEMBER_A}
AND role_row."type" = 'app'
AND (role_row."tenantId" IS NULL OR role_row."tenantId" = ${TENANT_A})
ORDER BY permission_row."name" ASC
`
);
expect(visibleGatewayPermissions).toEqual([
{
name: CHAT_PERMISSIONS.readOwnChannels,
roleTenantId: null,
assignmentTenantId: TENANT_A,
},
{
name: CHAT_PERMISSIONS.write,
roleTenantId: null,
assignmentTenantId: TENANT_A,
},
{
name: "files.read_own",
roleTenantId: null,
assignmentTenantId: TENANT_A,
},
{
name: "files.write",
roleTenantId: null,
assignmentTenantId: TENANT_A,
},
]);
const memberGatewayContext = { tenantId: TENANT_A, userId: MEMBER_A, sessionId: MEMBER_A_SESSION_ID } as const;
await expect(authorizeChatGatewayConnection(memberGatewayContext)).resolves.toBeUndefined();
await expect(assertMemberChannelAccess({ ...memberGatewayContext, chatId: CHAT_A })).resolves.toBeUndefined();
await expect(revalidateChatGatewayAccess({ ...memberGatewayContext, chatIds: [CHAT_A] })).resolves.toBeUndefined();
await expect(fillChatEventGap({ ...memberGatewayContext, chatId: CHAT_A, afterCursor: "0" })).resolves.toEqual({
status: "ok",
events: [],
nextCursor: "0",
hasMore: false,
});
await expect(
setChatMemberPreferences({
tenantId: TENANT_A,
userId: MEMBER_A,
permissions: READ_PERMISSIONS,
chatId: CHAT_A,
requestId: "chat_repo_rls_preferences_member_a",
isPinned: true,
notificationPreference: "muted",
})
).resolves.toMatchObject({ chatId: CHAT_A, isPinned: true, notificationPreference: "muted", changed: true });
await expect(
setChatMemberPreferences({
tenantId: TENANT_A,
userId: OUTSIDER_A,
permissions: READ_PERMISSIONS,
chatId: CHAT_A,
requestId: "chat_repo_rls_preferences_outsider_a",
isPinned: true,
})
).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(
setChatMemberPreferences({
tenantId: TENANT_B,
userId: MEMBER_B,
permissions: READ_PERMISSIONS,
chatId: CHAT_A,
requestId: "chat_repo_rls_preferences_member_b",
notificationPreference: "muted",
})
).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(authorizeChatGatewayConnection({ tenantId: TENANT_A, userId: MEMBER_A, sessionId: MEMBER_A_REVOKED_SESSION_ID })).rejects.toMatchObject({
code: "foundation.not_found",
});
const foreignTenantGatewayContext = { tenantId: TENANT_B, userId: MEMBER_B, sessionId: MEMBER_B_SESSION_ID } as const;
await expect(authorizeChatGatewayConnection(foreignTenantGatewayContext)).resolves.toBeUndefined();
await expect(assertMemberChannelAccess({ ...foreignTenantGatewayContext, chatId: CHAT_A })).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(fillChatEventGap({ ...foreignTenantGatewayContext, chatId: CHAT_A, afterCursor: "0" })).rejects.toMatchObject({
code: "foundation.not_found",
});
await admin.teamChatMember.update({
where: { chatId_userId: { chatId: CHAT_A, userId: MEMBER_A } },
data: { leftAt: new Date() },
});
try {
await expect(assertMemberChannelAccess({ ...memberGatewayContext, chatId: CHAT_A })).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(revalidateChatGatewayAccess({ ...memberGatewayContext, chatIds: [CHAT_A] })).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(fillChatEventGap({ ...memberGatewayContext, chatId: CHAT_A, afterCursor: "0" })).rejects.toMatchObject({
code: "foundation.not_found",
});
} finally {
await admin.teamChatMember.update({
where: { chatId_userId: { chatId: CHAT_A, userId: MEMBER_A } },
data: { leftAt: null },
});
}
});
it("filters and paginates the channel index before hydration without crossing tenant RLS", async () => {
const newerLastMessageAt = new Date("2026-07-15T12:00:00.000Z");
const olderLastMessageAt = new Date("2026-07-15T11:00:00.000Z");
await admin.user.create({
data: {
id: SEARCH_MEMBER_A,
email: "chat-repo-cursor-needle@example.test",
firstName: "Cursor",
lastName: "Needle",
active: true,
},
});
await admin.tenantUser.create({
data: {
id: "chat_repo_rls_membership_search_member_a",
tenantId: TENANT_A,
userId: SEARCH_MEMBER_A,
type: 0,
joined: 1,
status: 2,
},
});
await admin.teamChat.createMany({
data: [
{
id: PAGE_CHAT_NEWER,
tenantId: TENANT_A,
createdByUserId: MEMBER_A,
kind: "group",
name: "Newest candidate",
isPrivate: true,
eventStreamId: "chat_repo_rls_page_stream_newer",
lastMessageAt: newerLastMessageAt,
},
{
id: PAGE_CHAT_OLDER,
tenantId: TENANT_A,
createdByUserId: MEMBER_A,
kind: "group",
name: "Older candidate",
isPrivate: true,
eventStreamId: "chat_repo_rls_page_stream_older",
lastMessageAt: olderLastMessageAt,
},
{
id: PAGE_CHAT_FOREIGN,
tenantId: TENANT_B,
createdByUserId: MEMBER_B,
kind: "group",
name: "Cursor Needle foreign candidate",
isPrivate: true,
eventStreamId: "chat_repo_rls_page_stream_foreign",
lastMessageAt: new Date("2026-07-15T13:00:00.000Z"),
},
],
});
await admin.teamChatMember.createMany({
data: [
{
id: "chat_repo_rls_page_newer_viewer",
tenantId: TENANT_A,
chatId: PAGE_CHAT_NEWER,
userId: MEMBER_A,
isPinned: true,
notificationPref: "all_messages",
},
{
id: "chat_repo_rls_page_newer_search_member",
tenantId: TENANT_A,
chatId: PAGE_CHAT_NEWER,
userId: SEARCH_MEMBER_A,
notificationPref: "all_messages",
},
{
id: "chat_repo_rls_page_older_viewer",
tenantId: TENANT_A,
chatId: PAGE_CHAT_OLDER,
userId: MEMBER_A,
notificationPref: "all_messages",
},
{
id: "chat_repo_rls_page_older_search_member",
tenantId: TENANT_A,
chatId: PAGE_CHAT_OLDER,
userId: SEARCH_MEMBER_A,
notificationPref: "all_messages",
},
{
id: "chat_repo_rls_page_foreign_viewer",
tenantId: TENANT_B,
chatId: PAGE_CHAT_FOREIGN,
userId: MEMBER_B,
notificationPref: "all_messages",
},
],
});
await admin.teamChatMessage.create({
data: {
id: PAGE_MESSAGE_OLDER,
tenantId: TENANT_A,
chatId: PAGE_CHAT_OLDER,
authorUserId: SEARCH_MEMBER_A,
clientMessageId: "chat_repo_rls_page_message_client",
body: "Searchable message body needle",
bodyFormat: "markdown",
mentions: [],
linkPreviews: [],
createdAt: olderLastMessageAt,
},
});
try {
const context = { tenantId: TENANT_A, userId: MEMBER_A, permissions: READ_PERMISSIONS } as const;
const firstPage = await listMemberChannels({ ...context, query: " Cursor Needle ", limit: 1 });
expect(firstPage.channels.map((channel) => channel.id)).toEqual([PAGE_CHAT_NEWER]);
expect(firstPage.nextCursor).toEqual(expect.any(String));
const secondPage = await listMemberChannels({
...context,
query: "Cursor Needle",
limit: 1,
afterCursor: firstPage.nextCursor!,
});
expect(secondPage.channels.map((channel) => channel.id)).toEqual([PAGE_CHAT_OLDER]);
expect(secondPage.nextCursor).toBeNull();
expect([...firstPage.channels, ...secondPage.channels].some((channel) => channel.id === PAGE_CHAT_FOREIGN)).toBe(false);
await expect(listMemberChannels({ ...context, query: "Cursor Needle", view: "pinned" })).resolves.toMatchObject({
channels: [{ id: PAGE_CHAT_NEWER }],
nextCursor: null,
});
await expect(listMemberChannels({ ...context, query: "Searchable message body needle", view: "unread" })).resolves.toMatchObject({
channels: [
{
id: PAGE_CHAT_OLDER,
participants: [{ userId: SEARCH_MEMBER_A, displayName: "Cursor Needle", avatarUrl: null }],
unreadCount: 1,
hasUnreadMention: false,
},
],
nextCursor: null,
});
} finally {
await admin.teamChatMember.updateMany({
where: { chatId: { in: [PAGE_CHAT_NEWER, PAGE_CHAT_OLDER, PAGE_CHAT_FOREIGN] } },
data: { lastReadMessageId: null, lastReadAt: null },
});
await admin.teamChatMessage.deleteMany({ where: { id: PAGE_MESSAGE_OLDER } });
await admin.teamChatMember.deleteMany({ where: { chatId: { in: [PAGE_CHAT_NEWER, PAGE_CHAT_OLDER, PAGE_CHAT_FOREIGN] } } });
await admin.teamChat.deleteMany({ where: { id: { in: [PAGE_CHAT_NEWER, PAGE_CHAT_OLDER, PAGE_CHAT_FOREIGN] } } });
await admin.tenantUser.deleteMany({ where: { tenantId: TENANT_A, userId: SEARCH_MEMBER_A } });
await admin.user.deleteMany({ where: { id: SEARCH_MEMBER_A } });
}
});
it("keeps Files attachments tenant-bound and projects them only through an active channel membership", async () => {
const context = { tenantId: TENANT_A, userId: MEMBER_A, permissions: [...WRITE_PERMISSIONS, "files.write"] } as const;
await expect(
sendTopLevelChatMessage({
...context,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_foreign_attachment",
requestId: "chat_repo_rls_foreign_attachment_request",
body: "",
attachmentFileIds: [FILE_B],
})
).rejects.toMatchObject({ code: "foundation.not_found" });
const sent = await sendTopLevelChatMessage({
...context,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_owned_attachment",
requestId: "chat_repo_rls_owned_attachment_request",
body: "",
attachmentFileIds: [FILE_A],
});
expect(sent.message.attachmentIds).toEqual([FILE_A]);
await expect(
getMemberChannelDetail({ tenantId: TENANT_A, userId: MEMBER_A, permissions: READ_PERMISSIONS, chatId: CHAT_A })
).resolves.toMatchObject({
messages: [{ id: sent.message.id, attachmentIds: [FILE_A] }],
attachments: [{ messageId: sent.message.id, fileId: FILE_A, mimeType: "audio/webm", scanStatus: "clean" }],
});
await expect(admin.fileEntityLink.findMany({ where: { tenantId: TENANT_A, entityType: "chat_message", entityId: sent.message.id } })).resolves.toHaveLength(1);
await admin.fileEntityLink.deleteMany({ where: { tenantId: TENANT_A, entityType: "chat_message", entityId: sent.message.id } });
await admin.teamChatEvent.deleteMany({ where: { tenantId: TENANT_A, entityId: sent.message.id } });
await admin.teamChatMessage.delete({ where: { id: sent.message.id } });
await admin.teamChat.update({ where: { id: CHAT_A }, data: { lastMessageAt: null } });
});
it("combines PostgreSQL tenant RLS with active channel membership for every repository path", async () => {
const currentRole = await app.$queryRaw<Array<{ currentUser: string }>>`SELECT current_user AS "currentUser"`;
expect(currentRole).toEqual([{ currentUser: "hivegrid_app" }]);
await expect(app.teamChat.findMany({ where: { id: CHAT_A }, select: { id: true } })).resolves.toEqual([]);
await expect(app.teamChatMessage.findMany({ where: { chatId: CHAT_A }, select: { id: true } })).resolves.toEqual([]);
await expect(app.teamChatEvent.findMany({ where: { chatId: CHAT_A }, select: { id: true } })).resolves.toEqual([]);
const outsiderContext = { tenantId: TENANT_A, userId: OUTSIDER_A, permissions: READ_PERMISSIONS } as const;
await expect(listMemberChannels(outsiderContext)).resolves.toEqual({ channels: [], nextCursor: null });
await expect(getMemberChannelDetail({ ...outsiderContext, chatId: CHAT_A })).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(loadChatChannelSettings({ ...outsiderContext, chatId: CHAT_A })).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(fillChatEventGap({ ...outsiderContext, chatId: CHAT_A, afterCursor: "0" })).rejects.toMatchObject({
code: "foundation.not_found",
});
await expect(
sendTopLevelChatMessage({
tenantId: TENANT_A,
userId: OUTSIDER_A,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_outsider_send",
requestId: "chat_repo_rls_outsider_request",
body: "Must not be written",
})
).rejects.toMatchObject({ code: "foundation.not_found" });
const wrongTenantContext = { tenantId: TENANT_B, userId: MEMBER_B, permissions: READ_PERMISSIONS } as const;
await expect(listMemberChannels(wrongTenantContext)).resolves.toEqual({ channels: [], nextCursor: null });
await expect(getMemberChannelDetail({ ...wrongTenantContext, chatId: CHAT_A })).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(loadChatChannelSettings({ ...wrongTenantContext, chatId: CHAT_A })).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(fillChatEventGap({ ...wrongTenantContext, chatId: CHAT_A, afterCursor: "0" })).rejects.toMatchObject({
code: "foundation.not_found",
});
await expect(
sendTopLevelChatMessage({
tenantId: TENANT_B,
userId: MEMBER_B,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_cross_tenant_send",
requestId: "chat_repo_rls_cross_tenant_request",
body: "Must not cross tenants",
})
).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(countWrites(admin)).resolves.toEqual({ messages: 0, events: 0 });
const memberReadContext = { tenantId: TENANT_A, userId: MEMBER_A, permissions: READ_PERMISSIONS } as const;
const listed = await listMemberChannels(memberReadContext);
expect(listed.channels.map((channel) => channel.id)).toEqual([CHAT_A]);
expect(listed.channels[0]).toMatchObject({
eventCursor: "0",
participants: [],
unreadCount: 0,
hasUnreadMention: false,
});
await expect(getMemberChannelDetail({ ...memberReadContext, chatId: CHAT_A })).resolves.toMatchObject({
channel: {
id: CHAT_A,
participants: [{ userId: MEMBER_A, displayName: "Member A", avatarUrl: null }],
unreadCount: 0,
hasUnreadMention: false,
},
messages: [],
readReceipts: [],
olderMessageCursor: null,
eventCursor: "0",
});
await expect(loadChatChannelSettings({ ...memberReadContext, chatId: CHAT_A })).resolves.toMatchObject({
channel: { id: CHAT_A, kind: "group", privacy: "private", archivedAtIso: null },
members: [{ userId: MEMBER_A, roleInChat: "member" }],
candidateUsers: [],
capabilities: {
canManageMembers: false,
canManageAdmins: false,
canChangePrivacy: false,
canArchive: false,
canLeave: true,
isReadOnly: false,
},
});
const sent = await sendTopLevelChatMessage({
tenantId: TENANT_A,
userId: MEMBER_A,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: CLIENT_MESSAGE_ID,
requestId: REQUEST_ID,
body: "Restricted-role message",
});
expect(sent).toMatchObject({ replayed: false, message: { clientMessageId: CLIENT_MESSAGE_ID } });
expect(sent.event.cursor).toMatch(new RegExp(`^${STREAM_A}:[1-9]\\d*$`));
await expect(fillChatEventGap({ ...memberReadContext, chatId: CHAT_A, afterCursor: "0" })).resolves.toMatchObject({
status: "ok",
hasMore: false,
events: [{ cursor: sent.event.cursor }],
nextCursor: sent.event.cursor,
});
await expect(countWrites(admin)).resolves.toEqual({ messages: 1, events: 1 });
await expect(
markChatMessageRead({
...outsiderContext,
chatId: CHAT_A,
messageId: sent.message.id,
requestId: "chat_repo_rls_outsider_read",
})
).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(
markChatMessageRead({
...wrongTenantContext,
chatId: CHAT_A,
messageId: sent.message.id,
requestId: "chat_repo_rls_cross_tenant_read",
})
).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(
sendTopLevelChatMessage({
tenantId: TENANT_A,
userId: MEMBER_A,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_nonmember_mention",
requestId: "chat_repo_rls_nonmember_mention_request",
body: `Tenant membership alone must not allow <@user:${OUTSIDER_A}>`,
mentions: [{ type: "user", id: OUTSIDER_A, label: "Untrusted label" }],
})
).rejects.toMatchObject({ code: "chat.invalid_input" });
await expect(countWrites(admin)).resolves.toEqual({ messages: 1, events: 1 });
await admin.teamChatMember.create({
data: {
id: "chat_repo_rls_channel_outsider_a",
tenantId: TENANT_A,
chatId: CHAT_A,
userId: OUTSIDER_A,
notificationPref: "all_messages",
},
});
await admin.tenantUser.update({
where: { tenantId_userId: { tenantId: TENANT_A, userId: OUTSIDER_A } },
data: { status: 1 },
});
try {
await expect(
sendTopLevelChatMessage({
tenantId: TENANT_A,
userId: MEMBER_A,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_inactive_tenant_member_mention",
requestId: "chat_repo_rls_inactive_tenant_member_mention_request",
body: `Inactive tenant members must not resolve <@user:${OUTSIDER_A}>`,
mentions: [{ type: "user", id: OUTSIDER_A, label: "Untrusted label" }],
})
).rejects.toMatchObject({ code: "chat.invalid_input" });
} finally {
await admin.tenantUser.update({
where: { tenantId_userId: { tenantId: TENANT_A, userId: OUTSIDER_A } },
data: { status: 2 },
});
}
await admin.user.update({ where: { id: OUTSIDER_A }, data: { active: false } });
try {
await expect(
sendTopLevelChatMessage({
tenantId: TENANT_A,
userId: MEMBER_A,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_inactive_user_mention",
requestId: "chat_repo_rls_inactive_user_mention_request",
body: `Inactive users must not resolve <@user:${OUTSIDER_A}>`,
mentions: [{ type: "user", id: OUTSIDER_A, label: "Untrusted label" }],
})
).rejects.toMatchObject({ code: "chat.invalid_input" });
} finally {
await admin.user.update({ where: { id: OUTSIDER_A }, data: { active: true } });
}
const channelMemberMention = await sendTopLevelChatMessage({
tenantId: TENANT_A,
userId: MEMBER_A,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_channel_member_mention",
requestId: "chat_repo_rls_channel_member_mention_request",
body: `Active channel member <@user:${OUTSIDER_A}>`,
mentions: [{ type: "user", id: OUTSIDER_A, label: "Untrusted label" }],
});
expect(channelMemberMention.message.mentions).toEqual([{ type: "user", id: OUTSIDER_A, label: "Outsider A" }]);
const mentioned = await sendTopLevelChatMessage({
tenantId: TENANT_A,
userId: OUTSIDER_A,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_outsider_mention",
requestId: "chat_repo_rls_outsider_mention_request",
body: `Restricted-role <@user:${MEMBER_A}>`,
mentions: [{ type: "user", id: MEMBER_A, label: "Untrusted label" }],
});
const markedRead = await markChatMessageRead({
...memberReadContext,
chatId: CHAT_A,
messageId: mentioned.message.id,
requestId: "chat_repo_rls_member_a_read_request",
});
expect(markedRead).toMatchObject({
replayed: false,
event: {
event: CHAT_EVENT_NAMES.readReceipt,
data: { messageId: mentioned.message.id, userId: MEMBER_A },
},
});
await expect(
markChatMessageRead({
...memberReadContext,
chatId: CHAT_A,
messageId: mentioned.message.id,
requestId: "chat_repo_rls_member_a_read_retry",
})
).resolves.toMatchObject({ replayed: true, event: { cursor: markedRead.event.cursor } });
await expect(listMemberChannels(memberReadContext)).resolves.toMatchObject({
channels: [
{
id: CHAT_A,
eventCursor: markedRead.event.cursor,
participants: [{ userId: OUTSIDER_A, displayName: "Outsider A", avatarUrl: null }],
unreadCount: 0,
hasUnreadMention: false,
},
],
});
await expect(getMemberChannelDetail({ ...memberReadContext, chatId: CHAT_A })).resolves.toMatchObject({
readReceipts: [{ messageId: mentioned.message.id, userId: MEMBER_A }],
});
await expect(admin.teamChatRead.count({ where: { tenantId: TENANT_A, messageId: mentioned.message.id, userId: MEMBER_A } })).resolves.toBe(1);
await expect(countWrites(admin)).resolves.toEqual({ messages: 3, events: 4 });
await admin.teamChatMember.update({
where: { chatId_userId: { chatId: CHAT_A, userId: MEMBER_A } },
data: { leftAt: new Date() },
});
await expect(listMemberChannels(memberReadContext)).resolves.toEqual({ channels: [], nextCursor: null });
await expect(getMemberChannelDetail({ ...memberReadContext, chatId: CHAT_A })).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(fillChatEventGap({ ...memberReadContext, chatId: CHAT_A, afterCursor: sent.event.cursor })).rejects.toMatchObject({
code: "foundation.not_found",
});
await expect(
sendTopLevelChatMessage({
tenantId: TENANT_A,
userId: MEMBER_A,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_after_leave_send",
requestId: "chat_repo_rls_after_leave_request",
body: "Must not be written after leaving",
})
).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(
markChatMessageRead({
...memberReadContext,
chatId: CHAT_A,
messageId: mentioned.message.id,
requestId: "chat_repo_rls_after_leave_read",
})
).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(countWrites(admin)).resolves.toEqual({ messages: 3, events: 4 });
});
});
async function countWrites(admin: ReturnType<typeof createDbClient>): Promise<{ messages: number; events: number }> {
const [messages, events] = await Promise.all([
admin.teamChatMessage.count({ where: { tenantId: TENANT_A, chatId: CHAT_A } }),
admin.teamChatEvent.count({ where: { tenantId: TENANT_A, chatId: CHAT_A } }),
]);
return { messages, events };
}
async function cleanupFixtures(admin: ReturnType<typeof createDbClient>): Promise<void> {
await admin.teamChatMember.updateMany({
where: { tenantId: { in: [TENANT_A, TENANT_B] } },
data: { lastReadMessageId: null, lastReadAt: null },
});
await admin.teamChatEvent.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.fileEntityLink.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] }, entityType: "chat_message" } });
await admin.teamChatMessage.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.teamChatMember.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.teamChat.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.userSession.deleteMany({
where: { id: { in: [MEMBER_A_SESSION_ID, MEMBER_A_REVOKED_SESSION_ID, MEMBER_B_SESSION_ID] } },
});
await admin.userRole.deleteMany({ where: { id: { in: [MEMBER_A_ROLE_ID, OUTSIDER_A_ROLE_ID, MEMBER_B_ROLE_ID] } } });
await admin.rolePermission.deleteMany({ where: { roleId: GLOBAL_APP_ROLE_ID } });
await admin.role.deleteMany({ where: { OR: [{ id: GLOBAL_APP_ROLE_ID }, { tenantId: null, name: GLOBAL_APP_ROLE_NAME }] } });
await admin.file.deleteMany({ where: { id: { in: [FILE_A, FILE_B] } } });
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: [MEMBER_A, OUTSIDER_A, MEMBER_B, SEARCH_MEMBER_A] } } });
}