import fs from "node:fs"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { resolveRepoPath } from "~/utils/testing/repoPaths"; const dbMocks = vi.hoisted(() => ({ kontaktFindMany: vi.fn(), inboxLeadFindMany: vi.fn(), projektFindMany: vi.fn(), fileFindMany: vi.fn(), taskFindMany: vi.fn(), hrEmployeeProfileFindMany: vi.fn(), tenantUserFindMany: vi.fn(), projektMitgliedFindMany: vi.fn(), groupUserFindMany: vi.fn(), userRoleFindMany: vi.fn(), fileEntityLinkFindMany: vi.fn(), recentSearchFindMany: vi.fn(), recentSearchDeleteMany: vi.fn(), recentSearchCreate: vi.fn(), executeRaw: vi.fn(), })); const accessMocks = vi.hoisted(() => ({ permissions: ["search.use"] as string[], hasModule: true, moduleAccess: new Map(), })); const rlsMocks = vi.hoisted(() => ({ tenantIds: [] as string[] })); const searchMocks = vi.hoisted(() => ({ createSearchClient: vi.fn(() => ({})), searchWithFallback: vi.fn() })); const localeMocks = vi.hoisted(() => ({ getTranslations: vi.fn() })); vi.mock("~/locale/i18next.server", () => ({ getTranslations: localeMocks.getTranslations })); vi.mock("@hivegrid/search", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, createSearchClient: searchMocks.createSearchClient, searchWithFallback: searchMocks.searchWithFallback }; }); vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: vi.fn(async (tenantId: string, callback: (database: unknown) => Promise) => { rlsMocks.tenantIds.push(tenantId); return callback({ $executeRaw: dbMocks.executeRaw, kontakt: { findMany: dbMocks.kontaktFindMany }, inboxLead: { findMany: dbMocks.inboxLeadFindMany }, projekt: { findMany: dbMocks.projektFindMany }, projektMitglied: { findMany: dbMocks.projektMitgliedFindMany }, groupUser: { findMany: dbMocks.groupUserFindMany }, userRole: { findMany: dbMocks.userRoleFindMany }, fileEntityLink: { findMany: dbMocks.fileEntityLinkFindMany }, file: { findMany: dbMocks.fileFindMany }, task: { findMany: dbMocks.taskFindMany }, hrEmployeeProfile: { findMany: dbMocks.hrEmployeeProfileFindMany }, tenantUser: { findMany: dbMocks.tenantUserFindMany }, recentSearch: { findMany: dbMocks.recentSearchFindMany, deleteMany: dbMocks.recentSearchDeleteMany, create: dbMocks.recentSearchCreate, }, }); }), })); vi.mock("~/utils/loaders.middleware", () => ({ requireAuth: vi.fn(async () => undefined) })); vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: vi.fn(async () => "tenant_1") })); vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(async () => ({ userId: "user_1", lng: "de" })) })); vi.mock("~/utils/connector/tenantConnector.server", () => ({ tenantHasModule: vi.fn(async ({ moduleKey }: { moduleKey: string }) => accessMocks.moduleAccess.get(moduleKey) ?? accessMocks.hasModule), })); vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({ getPermissionsByUser: vi.fn(async () => accessMocks.permissions), })); import { GlobalSearchInputError, GlobalSearchUnavailableError, recordCommittedSearch, runGlobalSearch } from "./globalSearch.server"; describe("runGlobalSearch", () => { beforeEach(() => { vi.clearAllMocks(); process.env.SEARCH_BACKEND = "sql"; accessMocks.permissions = ["search.use"]; accessMocks.hasModule = true; accessMocks.moduleAccess.clear(); rlsMocks.tenantIds.length = 0; dbMocks.recentSearchFindMany.mockResolvedValue([]); dbMocks.recentSearchDeleteMany.mockResolvedValue({ count: 0 }); dbMocks.recentSearchCreate.mockResolvedValue({}); dbMocks.executeRaw.mockResolvedValue(1); dbMocks.kontaktFindMany.mockResolvedValue([]); dbMocks.inboxLeadFindMany.mockResolvedValue([]); dbMocks.projektFindMany.mockResolvedValue([]); dbMocks.projektMitgliedFindMany.mockResolvedValue([]); dbMocks.groupUserFindMany.mockResolvedValue([]); dbMocks.userRoleFindMany.mockResolvedValue([]); dbMocks.fileEntityLinkFindMany.mockResolvedValue([]); dbMocks.fileFindMany.mockResolvedValue([]); dbMocks.taskFindMany.mockResolvedValue([]); dbMocks.hrEmployeeProfileFindMany.mockResolvedValue([]); dbMocks.tenantUserFindMany.mockResolvedValue([]); searchMocks.searchWithFallback.mockResolvedValue({ hits: [], estimatedTotalHits: 0, processingTimeMs: 0 }); localeMocks.getTranslations.mockResolvedValue({ t: (key: string) => `translated:${key}`, locale: "en" }); delete process.env.MEILI_URL; }); it("localizes the latency hint for the current request", async () => { const request = new Request("https://app.example.test/acme/search/api?q="); const result = await runGlobalSearch({ request, params: { tenant: "acme" }, query: "" }); expect(localeMocks.getTranslations).toHaveBeenCalledWith(request); expect(result.latencyHint).toBe("translated:search.latencyHint"); }); it("requires entity permissions in addition to search.use", async () => { const result = await runGlobalSearch({ request: new Request("https://app.example.test/acme/search?q=ada"), params: { tenant: "acme" }, query: "ada", }); expect(result.results).toEqual([]); expect(result.hiddenEntityTypes).toContain("contact"); expect(dbMocks.kontaktFindMany).not.toHaveBeenCalled(); expect(dbMocks.executeRaw).not.toHaveBeenCalled(); expect(rlsMocks.tenantIds).toEqual(["tenant_1", "tenant_1"]); }); it("does not load project or task principals for an empty search", async () => { accessMocks.permissions = ["search.use", "projects.read_own_member", "files.read_own", "tasks.read_own"]; const result = await runGlobalSearch({ request: new Request("https://app.example.test/acme/search/api?q="), params: { tenant: "acme" }, query: "", }); expect(result.results).toEqual([]); expect(dbMocks.userRoleFindMany).not.toHaveBeenCalled(); expect(dbMocks.groupUserFindMany).not.toHaveBeenCalled(); expect(dbMocks.projektMitgliedFindMany).not.toHaveBeenCalled(); }); it("does not load unrelated principals for a contact-only search", async () => { accessMocks.permissions = ["search.use", "crm.read_all", "projects.read_own_member", "files.read_own", "tasks.read_own"]; await runGlobalSearch({ request: new Request("https://app.example.test/acme/search/api?q=ada&type=contact"), params: { tenant: "acme" }, query: "ada", entityTypes: ["contact"], }); expect(dbMocks.userRoleFindMany).not.toHaveBeenCalled(); expect(dbMocks.groupUserFindMany).not.toHaveBeenCalled(); expect(dbMocks.projektMitgliedFindMany).not.toHaveBeenCalled(); }); it.each([ ["contact", "crm-basic", "crm.read_all", "kontaktFindMany"], ["company", "crm-basic", "crm.read_all", "kontaktFindMany"], ["lead", "leads", "leads.read_all", "inboxLeadFindMany"], ["project", "projects", "projects.read_all", "projektFindMany"], ["file", "files", "files.read_all", "fileFindMany"], ["task", "tasks", "tasks.read_all", "taskFindMany"], ["employee", "hr", "hr.read_all", "hrEmployeeProfileFindMany"], ["user", "users", "app.settings.members.view", "tenantUserFindMany"], ] as const)("hides %s results when the authoritative %s module is disabled", async (entityType, moduleKey, permission, dbMockName) => { accessMocks.permissions = ["search.use", permission]; accessMocks.moduleAccess.set(moduleKey, false); const result = await runGlobalSearch({ request: new Request(`https://app.example.test/acme/search/api?q=ada&type=${entityType}`), params: { tenant: "acme" }, query: "ada", entityTypes: [entityType], }); expect(result.results).toEqual([]); expect(result.hiddenEntityTypes).toContain(entityType); expect(dbMocks[dbMockName]).not.toHaveBeenCalled(); }); it("owner-filters CRM contacts when the caller only has crm.read_own", async () => { accessMocks.permissions = ["search.use", "crm.read_own"]; dbMocks.kontaktFindMany.mockResolvedValueOnce([ { id: "kontakt_1", vorname: "Ada", nachname: "Lovelace", orgName: null, primaerEmail: "ada@example.test", updatedAt: new Date("2026-07-01T10:00:00.000Z"), }, ]); const result = await runGlobalSearch({ request: new Request("https://app.example.test/acme/search?q=ada"), params: { tenant: "acme" }, query: "ada", entityTypes: ["contact"], }); expect(result.results[0]).toMatchObject({ id: "kontakt_1", entityType: "contact", permissionSubject: "crm.read_own", }); expect(dbMocks.kontaktFindMany).toHaveBeenCalledWith( expect.objectContaining({ where: expect.objectContaining({ tenantId: "tenant_1", AND: expect.arrayContaining([expect.objectContaining({ zustaendigerUserId: "user_1" })]), }), }) ); expect(JSON.stringify(dbMocks.kontaktFindMany.mock.calls[0]?.[0]?.where)).not.toContain("createdByUserId"); expect(dbMocks.executeRaw).not.toHaveBeenCalled(); }); it("limits employee search to self and direct reports for hr.read_own", async () => { accessMocks.permissions = ["search.use", "hr.read_own"]; dbMocks.tenantUserFindMany .mockResolvedValueOnce([{ userId: "employee_1" }, { userId: "employee_2" }]) .mockResolvedValueOnce([ { userId: "employee_1", user: { firstName: "Ada", lastName: "Lovelace", email: "ada@example.test" }, }, ]); dbMocks.hrEmployeeProfileFindMany.mockResolvedValueOnce([ { userId: "employee_1", position: "Engineer", team: "Platform", updatedAt: new Date("2026-07-20T10:00:00.000Z"), }, ]); const result = await runGlobalSearch({ request: new Request("https://app.example.test/acme/search?q=ada&type=employee"), params: { tenant: "acme" }, query: "ada", entityTypes: ["employee"], }); expect(result.results[0]).toMatchObject({ id: "employee_1", entityType: "employee", title: "Ada Lovelace", subtitle: "Engineer · Platform · ada@example.test", href: "/acme/hr/directory/employee_1", permissionSubject: "hr.read_own", }); expect(dbMocks.hrEmployeeProfileFindMany).toHaveBeenCalledWith( expect.objectContaining({ where: expect.objectContaining({ tenantId: "tenant_1", AND: expect.arrayContaining([ { OR: [{ userId: "user_1" }, { managerUserId: "user_1" }] }, ]), }), }) ); }); it("fails closed with a bounded search-unavailable error when the SQL authority is unavailable", async () => { accessMocks.permissions = ["search.use", "crm.read_all"]; const databaseError = new Error("database unavailable"); dbMocks.kontaktFindMany.mockRejectedValueOnce(databaseError); await expect( runGlobalSearch({ request: new Request("https://app.example.test/acme/search/api?q=ada&type=contact"), params: { tenant: "acme" }, query: "ada", entityTypes: ["contact"], }) ).rejects.toMatchObject>({ message: "search_unavailable", cause: databaseError, }); }); it("echoes request identity and canonical filters without writing on GET searches", async () => { accessMocks.permissions = ["search.use", "crm.read_all", "projects.read_all"]; const result = await runGlobalSearch({ request: new Request("https://app.example.test/acme/search/api?q=Ada&requestId=req-2"), params: { tenant: "acme" }, query: " Ada ", limit: 8, entityTypes: ["project", "contact", "project"], requestId: "req-2", }); expect(result).toMatchObject({ query: "Ada", requestedEntityTypes: ["contact", "project"], requestId: "req-2", requestKey: "Ada|contact,project|8", }); expect(dbMocks.executeRaw).not.toHaveBeenCalled(); expect(dbMocks.recentSearchCreate).not.toHaveBeenCalled(); }); it("fairly interleaves SQL results across entity types before applying the result limit", async () => { accessMocks.permissions = ["search.use", "crm.read_all", "projects.read_all", "files.read_all"]; dbMocks.kontaktFindMany.mockResolvedValueOnce([ { id: "contact_1", vorname: "Ada", nachname: "One", orgName: null, primaerEmail: "ada.one@example.test", updatedAt: new Date("2026-07-10T10:00:00.000Z"), }, { id: "contact_2", vorname: "Ada", nachname: "Two", orgName: null, primaerEmail: "ada.two@example.test", updatedAt: new Date("2026-07-09T10:00:00.000Z"), }, { id: "contact_3", vorname: "Ada", nachname: "Three", orgName: null, primaerEmail: "ada.three@example.test", updatedAt: new Date("2026-07-08T10:00:00.000Z"), }, ]); dbMocks.projektFindMany.mockResolvedValueOnce([ { id: "project_1", projektNummer: "P-1", projektname: "Ada Project", beschreibung: null, updatedAt: new Date("2026-07-07T10:00:00.000Z"), }, ]); dbMocks.fileFindMany.mockResolvedValueOnce([ { id: "file_1", displayName: "ada.pdf", mimeType: "application/pdf", updatedAt: new Date("2026-07-06T10:00:00.000Z"), }, ]); const result = await runGlobalSearch({ request: new Request("https://app.example.test/acme/search/api?q=ada&limit=3"), params: { tenant: "acme" }, query: "ada", limit: 3, entityTypes: ["contact", "project", "file"], }); expect(result.results.map(({ entityType, id }) => `${entityType}:${id}`)).toEqual(["contact:contact_1", "project:project_1", "file:file_1"]); }); it("fairly interleaves types while preserving Meili relevance order and cross-source deduplication", async () => { process.env.SEARCH_BACKEND = "meili"; process.env.MEILI_URL = "http://meili.test"; accessMocks.permissions = ["search.use", "crm.read_all", "projects.read_all", "files.read_all"]; searchMocks.searchWithFallback .mockResolvedValueOnce({ hits: [ { document: { id: "contact_1", firstName: "Ada", lastName: "One", email: "ada.one@example.test", updatedAt: "2026-07-01T10:00:00.000Z", }, }, { document: { id: "contact_2", firstName: "Ada", lastName: "Two", email: "ada.two@example.test", updatedAt: "2026-07-10T10:00:00.000Z", }, }, { document: { id: "contact_3", firstName: "Ada", lastName: "Three", email: "ada.three@example.test", updatedAt: "2026-07-08T10:00:00.000Z", }, }, ], estimatedTotalHits: 3, processingTimeMs: 1, }) .mockResolvedValueOnce({ hits: [{ document: { id: "project_1", name: "Ada Project", projectNumber: "P-1", updatedAt: "2026-07-07T10:00:00.000Z" } }], estimatedTotalHits: 1, processingTimeMs: 1, }) .mockResolvedValueOnce({ hits: [{ document: { id: "file_1", displayName: "ada.pdf", mimeType: "application/pdf", updatedAt: "2026-07-06T10:00:00.000Z" } }], estimatedTotalHits: 1, processingTimeMs: 1, }); dbMocks.kontaktFindMany.mockImplementation(async ({ where }) => { if (where.id?.in) return where.id.in.map((id: string) => ({ id })); return [ { id: "contact_1", vorname: "Ada", nachname: "One", orgName: null, primaerEmail: "ada.one@example.test", updatedAt: new Date("2026-07-10T10:00:00.000Z"), }, ]; }); dbMocks.projektFindMany.mockImplementation(async ({ where }) => (where.id?.in ? where.id.in.map((id: string) => ({ id })) : [])); dbMocks.fileFindMany.mockImplementation(async ({ where }) => (where.id?.in ? where.id.in.map((id: string) => ({ id })) : [])); const result = await runGlobalSearch({ request: new Request("https://app.example.test/acme/search/api?q=ada&limit=4"), params: { tenant: "acme" }, query: "ada", limit: 4, entityTypes: ["contact", "project", "file"], }); const resultKeys = result.results.map(({ entityType, id }) => `${entityType}:${id}`); expect(new Set(resultKeys.slice(0, 3))).toEqual(new Set(["contact:contact_1", "project:project_1", "file:file_1"])); expect(resultKeys.indexOf("contact:contact_1")).toBeLessThan(resultKeys.indexOf("contact:contact_2")); expect(result.results.filter(({ entityType, id }) => entityType === "contact" && id === "contact_1")).toHaveLength(1); }); it("rejects too-short queries and invalid entity types after the search access gate", async () => { await expect( runGlobalSearch({ request: new Request("https://app.example.test/acme/search/api?q=a"), params: { tenant: "acme" }, query: "a", }) ).rejects.toMatchObject>({ code: "query_too_short" }); await expect( runGlobalSearch({ request: new Request("https://app.example.test/acme/search/api?q=ada&type=invoice"), params: { tenant: "acme" }, query: "ada", entityTypes: ["invoice"], }) ).rejects.toMatchObject>({ code: "invalid_entity_types" }); expect(dbMocks.executeRaw).not.toHaveBeenCalled(); }); it("drops stale Meili candidates for every entity type unless current SQL visibility confirms them", async () => { process.env.SEARCH_BACKEND = "meili"; process.env.MEILI_URL = "http://meili.test"; accessMocks.permissions = [ "search.use", "crm.read_own", "leads.read_own", "projects.read_own", "files.read_own", "tasks.read_own", "app.settings.members.view", ]; const cases = [ { type: "contact", document: { id: "contact_stale", firstName: "Ada", lastName: "Old", email: "ada@example.test" } }, { type: "company", document: { id: "company_stale", company: "Old GmbH", email: "old@example.test" } }, { type: "lead", document: { id: "lead_stale", firstName: "Lee", lastName: "Old", email: "lead@example.test" } }, { type: "project", document: { id: "project_stale", name: "Old Project", projectNumber: "P-1" } }, { type: "file", document: { id: "file_stale", displayName: "old.pdf", mimeType: "application/pdf" } }, { type: "task", document: { id: "task_stale", title: "Old Task", status: "open" } }, { type: "user", document: { id: "user_stale", firstName: "Old", lastName: "Member", email: "old@example.test" } }, ] as const; for (const testCase of cases) { searchMocks.searchWithFallback.mockResolvedValueOnce({ hits: [{ document: testCase.document }], estimatedTotalHits: 1, processingTimeMs: 1, }); const result = await runGlobalSearch({ request: new Request(`https://app.example.test/acme/search/api?q=old&type=${testCase.type}`), params: { tenant: "acme" }, query: "old", entityTypes: [testCase.type], }); expect(result.results, testCase.type).toEqual([]); } expect(rlsMocks.tenantIds.every((tenantId) => tenantId === "tenant_1")).toBe(true); }); it("uses current project membership for projects.read_own_member", async () => { accessMocks.permissions = ["search.use", "projects.read_own_member"]; dbMocks.userRoleFindMany.mockResolvedValueOnce([{ roleId: "role_1" }]); dbMocks.groupUserFindMany.mockResolvedValueOnce([{ groupId: "group_1" }]); dbMocks.projektFindMany.mockResolvedValueOnce([ { id: "project_1", projektNummer: "P-1", projektname: "Member Project", beschreibung: null, updatedAt: new Date("2026-07-01T10:00:00.000Z"), }, ]); const result = await runGlobalSearch({ request: new Request("https://app.example.test/acme/search/api?q=member&type=project"), params: { tenant: "acme" }, query: "member", entityTypes: ["project"], }); expect(result.results).toEqual([expect.objectContaining({ id: "project_1", entityType: "project" })]); expect(dbMocks.projektMitgliedFindMany).not.toHaveBeenCalled(); const where = dbMocks.projektFindMany.mock.calls[0]?.[0].where; expect(where.AND[0]).toEqual({ AND: [ { OR: [ { mitglieder: { some: { tenantId: "tenant_1", archivedAt: null, OR: [{ userId: "user_1" }, { groupId: { in: ["group_1"] } }], }, }, }, ], }, { pipeline: { accessRules: { none: { tenantId: "tenant_1", kannSehen: false, OR: [ { principalType: "user", principalId: "user_1" }, { principalType: "role", principalId: "role_1" }, { principalType: "group", principalId: "group_1" }, ], }, }, }, }, ], }); }); it("uses only the project-lead field for projects.read_own_pl in SQL and Meili", async () => { process.env.SEARCH_BACKEND = "meili"; process.env.MEILI_URL = "http://meili.test"; accessMocks.permissions = ["search.use", "projects.read_own_pl"]; await runGlobalSearch({ request: new Request("https://app.example.test/acme/search/api?q=project&type=project"), params: { tenant: "acme" }, query: "project", entityTypes: ["project"], }); const where = dbMocks.projektFindMany.mock.calls[0]?.[0].where; expect(where.AND[0]).toMatchObject({ AND: [{ OR: [{ projektleiterId: "user_1" }] }, { pipeline: { accessRules: { none: { tenantId: "tenant_1", kannSehen: false } } } }], }); expect(searchMocks.searchWithFallback).toHaveBeenCalledWith( expect.objectContaining({ options: expect.objectContaining({ extraFilters: ['projectLeadId = "user_1"'] }), }) ); }); it("matches the authoritative own-visibility rules for leads, unlinked files, and task groups", async () => { accessMocks.permissions = ["search.use", "leads.read_own"]; await runGlobalSearch({ request: new Request("https://app.example.test/acme/search/api?q=lead&type=lead"), params: { tenant: "acme" }, query: "lead", entityTypes: ["lead"], }); expect(dbMocks.inboxLeadFindMany).toHaveBeenCalledWith( expect.objectContaining({ where: expect.objectContaining({ AND: expect.arrayContaining([{ zustaendigerUserId: "user_1" }]) }), }) ); accessMocks.permissions = ["search.use", "files.read_own"]; await runGlobalSearch({ request: new Request("https://app.example.test/acme/search/api?q=file&type=file"), params: { tenant: "acme" }, query: "file", entityTypes: ["file"], }); const unlinkedFileVisibility = dbMocks.fileFindMany.mock.calls[0]?.[0].where.AND[0]; expect(unlinkedFileVisibility.AND[0].OR).toEqual(expect.arrayContaining([{ createdByUserId: "user_1" }, { assignedToUserId: "user_1" }])); expect(dbMocks.fileEntityLinkFindMany).not.toHaveBeenCalled(); accessMocks.permissions = ["search.use", "tasks.read_own"]; dbMocks.groupUserFindMany.mockResolvedValueOnce([{ groupId: "group_1" }]); await runGlobalSearch({ request: new Request("https://app.example.test/acme/search/api?q=task&type=task"), params: { tenant: "acme" }, query: "task", entityTypes: ["task"], }); expect(dbMocks.taskFindMany).toHaveBeenCalledWith( expect.objectContaining({ where: expect.objectContaining({ AND: expect.arrayContaining([expect.objectContaining({ OR: expect.arrayContaining([{ assignedToGroupId: { in: ["group_1"] } }]) })]), }), }) ); expect(dbMocks.userRoleFindMany).not.toHaveBeenCalled(); expect(dbMocks.projektMitgliedFindMany).not.toHaveBeenCalled(); }); it("shows a project-linked file only when the linked project passes membership and pipeline visibility", async () => { accessMocks.permissions = ["search.use", "files.read_own", "projects.read_own_member"]; dbMocks.userRoleFindMany.mockResolvedValueOnce([{ roleId: "role_1" }]); dbMocks.groupUserFindMany.mockResolvedValueOnce([{ groupId: "group_1" }]); dbMocks.projektFindMany.mockResolvedValueOnce([{ id: "project_1" }]); dbMocks.fileFindMany.mockResolvedValueOnce([ { id: "file_1", displayName: "Project plan.pdf", mimeType: "application/pdf", updatedAt: new Date("2026-07-01T10:00:00.000Z"), }, ]); const result = await runGlobalSearch({ request: new Request("https://app.example.test/acme/search/api?q=project&type=file"), params: { tenant: "acme" }, query: "project", entityTypes: ["file"], }); expect(result.results).toEqual([expect.objectContaining({ id: "file_1", entityType: "file" })]); expect(dbMocks.projektFindMany.mock.calls[0]?.[0].where).toMatchObject({ tenantId: "tenant_1", AND: [ { OR: [ { mitglieder: { some: { tenantId: "tenant_1", archivedAt: null, OR: [{ userId: "user_1" }, { groupId: { in: ["group_1"] } }], }, }, }, ], }, { pipeline: { accessRules: { none: { tenantId: "tenant_1", kannSehen: false, OR: [ { principalType: "user", principalId: "user_1" }, { principalType: "role", principalId: "role_1" }, { principalType: "group", principalId: "group_1" }, ], }, }, }, }, ], }); expect(dbMocks.fileEntityLinkFindMany).not.toHaveBeenCalled(); const linkedFileVisibility = dbMocks.fileFindMany.mock.calls[0]?.[0].where.AND[0]; expect(linkedFileVisibility.AND[0].OR).toEqual( expect.arrayContaining([ { createdByUserId: "user_1" }, { assignedToUserId: "user_1" }, { links: { some: { tenantId: "tenant_1", entityType: "project", entityId: { in: ["project_1"] }, }, }, }, ]) ); }); it("records a committed search privately, deduplicates filters, and bounds retention", async () => { dbMocks.kontaktFindMany.mockResolvedValueOnce([{ id: "kontakt_1" }]); dbMocks.recentSearchFindMany .mockResolvedValueOnce([ { id: "duplicate", appliedFilters: { entityTypes: ["contact", "project"] } }, { id: "other-filter", appliedFilters: { entityTypes: ["contact"] } }, ]) .mockResolvedValueOnce([{ id: "overflow" }]); const result = await recordCommittedSearch({ ctx: { tenantId: "tenant_1", tenantSlug: "acme", userId: "user_1", permissions: ["search.use", "crm.read_all"] }, query: " Ada ", entityTypes: ["project", "contact", "project"], resultCount: "7", selectedEntityType: "contact", selectedEntityId: "kontakt_1", }); expect(result).toEqual({ recorded: true, requestKey: "Ada|contact,project|*" }); expect(dbMocks.recentSearchFindMany).toHaveBeenNthCalledWith( 1, expect.objectContaining({ where: { tenantId: "tenant_1", userId: "user_1", queryText: "Ada" } }) ); expect(dbMocks.recentSearchFindMany).toHaveBeenNthCalledWith( 2, expect.objectContaining({ where: expect.objectContaining({ tenantId: "tenant_1", userId: "user_1", createdAt: { gte: expect.any(Date) } }), skip: 49, }) ); expect(dbMocks.recentSearchDeleteMany).toHaveBeenCalledWith( expect.objectContaining({ where: expect.objectContaining({ tenantId: "tenant_1", userId: "user_1", OR: expect.arrayContaining([expect.objectContaining({ id: { in: expect.arrayContaining(["duplicate", "overflow"]) } })]), }), }) ); expect(dbMocks.recentSearchCreate).toHaveBeenCalledWith({ data: { tenantId: "tenant_1", userId: "user_1", queryText: "Ada", resultCount: 7, appliedFilters: { entityTypes: ["contact", "project"] }, }, }); expect(dbMocks.executeRaw).toHaveBeenCalledTimes(1); expect(dbMocks.executeRaw.mock.invocationCallOrder[0]).toBeLessThan(dbMocks.recentSearchFindMany.mock.invocationCallOrder[0] ?? Number.MAX_SAFE_INTEGER); expect(rlsMocks.tenantIds).toEqual(["tenant_1"]); }); it("revalidates a projects.read_own_pl selection only against projektleiterId", async () => { dbMocks.projektFindMany.mockResolvedValueOnce([{ id: "project_1" }]); await expect( recordCommittedSearch({ ctx: { tenantId: "tenant_1", tenantSlug: "acme", userId: "user_1", permissions: ["search.use", "projects.read_own_pl"] }, query: "Project", entityTypes: ["project"], resultCount: 1, selectedEntityType: "project", selectedEntityId: "project_1", }) ).resolves.toEqual({ recorded: true, requestKey: "Project|project|*" }); expect(dbMocks.projektFindMany.mock.calls[0]?.[0].where).toMatchObject({ AND: [{ OR: [{ projektleiterId: "user_1" }] }, { pipeline: { accessRules: { none: { tenantId: "tenant_1", kannSehen: false } } } }], }); }); it("rejects a committed selection when its authoritative module is disabled", async () => { accessMocks.moduleAccess.set("crm-basic", false); dbMocks.kontaktFindMany.mockResolvedValueOnce([{ id: "kontakt_1" }]); await expect( recordCommittedSearch({ ctx: { tenantId: "tenant_1", tenantSlug: "acme", userId: "user_1", permissions: ["search.use", "crm.read_all"] }, query: "Ada", entityTypes: ["contact"], resultCount: 1, selectedEntityType: "contact", selectedEntityId: "kontakt_1", }) ).rejects.toMatchObject>({ code: "invalid_selection" }); expect(dbMocks.kontaktFindMany).not.toHaveBeenCalled(); expect(rlsMocks.tenantIds).toEqual([]); }); it("does not block result navigation when persisting search history fails", async () => { dbMocks.kontaktFindMany.mockResolvedValueOnce([{ id: "kontakt_1" }]); dbMocks.recentSearchCreate.mockRejectedValueOnce(new Error("database unavailable")); await expect( recordCommittedSearch({ ctx: { tenantId: "tenant_1", tenantSlug: "acme", userId: "user_1", permissions: ["search.use", "crm.read_all"] }, query: "Ada", entityTypes: ["contact"], resultCount: 1, selectedEntityType: "contact", selectedEntityId: "kontakt_1", }) ).resolves.toEqual({ recorded: false, requestKey: "Ada|contact|*" }); }); it("rejects a creator-only contact after reassignment before taking the history lock", async () => { await expect( recordCommittedSearch({ ctx: { tenantId: "tenant_1", tenantSlug: "acme", userId: "user_1", permissions: ["search.use", "crm.read_own"] }, query: "Ada", entityTypes: ["contact"], resultCount: 1, selectedEntityType: "contact", selectedEntityId: "kontakt_reassigned", }) ).rejects.toMatchObject>({ code: "invalid_selection" }); expect(dbMocks.kontaktFindMany).toHaveBeenCalledWith({ where: { tenantId: "tenant_1", id: { in: ["kontakt_reassigned"] }, archivedAt: null, kontaktTyp: "privatperson", zustaendigerUserId: "user_1", }, select: { id: true }, }); expect(JSON.stringify(dbMocks.kontaktFindMany.mock.calls[0]?.[0]?.where)).not.toContain("createdByUserId"); expect(dbMocks.executeRaw).not.toHaveBeenCalled(); expect(dbMocks.recentSearchCreate).not.toHaveBeenCalled(); }); it("maps an unsupported selected entity type to invalid_selection", async () => { await expect( recordCommittedSearch({ ctx: { tenantId: "tenant_1", tenantSlug: "acme", userId: "user_1", permissions: ["search.use", "crm.read_all"] }, query: "Ada", entityTypes: ["contact"], resultCount: 1, selectedEntityType: "invoice", selectedEntityId: "invoice_1", }) ).rejects.toMatchObject>({ code: "invalid_selection" }); expect(rlsMocks.tenantIds).toEqual([]); }); it("rejects invalid committed-search payloads before opening a transaction", async () => { await expect( recordCommittedSearch({ ctx: { tenantId: "tenant_1", tenantSlug: "acme", userId: "user_1", permissions: ["search.use", "crm.read_all"] }, query: "Ada", entityTypes: ["contact"], resultCount: 51, selectedEntityType: "contact", selectedEntityId: "kontakt_1", }) ).rejects.toMatchObject>({ code: "invalid_result_count" }); expect(rlsMocks.tenantIds).toEqual([]); expect(dbMocks.executeRaw).not.toHaveBeenCalled(); }); }); describe("search RLS rollout artifact", () => { it("uses the canonical tenant GUC, grants the restricted role, and documents a full inverse", () => { const sql = fs.readFileSync(resolveRepoPath("prisma/rls/search-isolation.sql"), "utf8"); expect(sql).toContain("current_setting('app.tenant_id', true)"); expect(sql).not.toContain("app.current_tenant_id"); expect(sql).toContain('GRANT SELECT, INSERT, UPDATE, DELETE ON "SearchIndexEntry", "RecentSearch" TO hivegrid_app;'); expect(sql).toContain('REVOKE SELECT, INSERT, UPDATE, DELETE ON "SearchIndexEntry", "RecentSearch" FROM hivegrid_app;'); expect(sql).toContain('ALTER TABLE "SearchIndexEntry" DISABLE ROW LEVEL SECURITY;'); expect(sql).toContain('ALTER TABLE "RecentSearch" DISABLE ROW LEVEL SECURITY;'); }); });