396 lines
15 KiB
TypeScript
396 lines
15 KiB
TypeScript
import { describe, expect, it, vi } from "vitest";
|
|
|
|
import type { McpToolContext } from "./context.js";
|
|
import { decodeCursor } from "./pagination.js";
|
|
import { getVisibleContactDetail, listVisibleActivities, searchVisibleProjects } from "./read-tools-backend.js";
|
|
|
|
function contextWith(tx: Record<string, unknown>, permissions: string[]): McpToolContext {
|
|
const transaction = vi.fn(async (callback: (transactionClient: Record<string, unknown>) => Promise<unknown>) => callback(tx));
|
|
return {
|
|
principal: {
|
|
credential: { kind: "oauth", id: "token_1", name: "Test client" },
|
|
tenantId: "tenant_1",
|
|
tenantSlug: "acme",
|
|
userId: "user_1",
|
|
scopes: ["mcp:read"],
|
|
permissions,
|
|
},
|
|
readDb: { $transaction: transaction } as unknown as McpToolContext["readDb"],
|
|
writeDb: {} as McpToolContext["writeDb"],
|
|
request: { id: "request_1", ip: "127.0.0.1" },
|
|
};
|
|
}
|
|
|
|
function rlsExecutor() {
|
|
return vi.fn(async () => 1);
|
|
}
|
|
|
|
function firstCallArgument(mock: unknown): unknown {
|
|
return (mock as { mock: { calls: unknown[][] } }).mock.calls[0]?.[0];
|
|
}
|
|
|
|
describe("MCP read backend", () => {
|
|
it("searches member-visible projects, applies explicit user pipeline denies and omits monetary fields", async () => {
|
|
const createdAt = new Date("2026-07-12T10:00:00.000Z");
|
|
const olderCreatedAt = new Date("2026-07-11T10:00:00.000Z");
|
|
const projectFindMany = vi.fn(async () => [
|
|
{
|
|
id: "project_member",
|
|
projektNummer: "P-100",
|
|
projektname: "Visible project",
|
|
projekttyp: "SHK",
|
|
prioritaet: "hoch",
|
|
zustaendigePersonId: "owner_2",
|
|
projektleiterId: "lead_2",
|
|
deadline: new Date("2026-08-01T00:00:00.000Z"),
|
|
createdAt,
|
|
updatedAt: createdAt,
|
|
pipeline: { id: "pipeline_open", name: "Sales", typHint: "sales" },
|
|
stage: { id: "stage_new", name: "Neu", stageKind: "offen" },
|
|
potenziellerAuftragswert: "999999.00",
|
|
auftragsvolumen: "888888.00",
|
|
},
|
|
{
|
|
id: "project_next",
|
|
projektNummer: "P-099",
|
|
projektname: "Next project",
|
|
projekttyp: null,
|
|
prioritaet: "normal",
|
|
zustaendigePersonId: null,
|
|
projektleiterId: null,
|
|
deadline: null,
|
|
createdAt: olderCreatedAt,
|
|
updatedAt: olderCreatedAt,
|
|
pipeline: { id: "pipeline_open", name: "Sales", typHint: "sales" },
|
|
stage: { id: "stage_new", name: "Neu", stageKind: "offen" },
|
|
},
|
|
]);
|
|
const tx = {
|
|
$executeRaw: rlsExecutor(),
|
|
groupUser: { findMany: vi.fn(async () => [{ groupId: "group_1" }]) },
|
|
projektMitglied: { findMany: vi.fn() },
|
|
pipelineAccess: { findMany: vi.fn(async () => [{ pipelineId: "pipeline_denied" }]) },
|
|
projekt: { findMany: projectFindMany },
|
|
};
|
|
const ctx = contextWith(tx, ["projects.read_own_member"]);
|
|
|
|
const result = await searchVisibleProjects(ctx, {
|
|
query: "Visible",
|
|
pipelineId: "pipeline_open",
|
|
ownerUserId: "owner_2",
|
|
limit: 1,
|
|
});
|
|
|
|
expect(tx.$executeRaw).toHaveBeenCalledOnce();
|
|
expect(tx.$executeRaw).toHaveBeenCalledWith(expect.anything(), "tenant_1");
|
|
expect(projectFindMany).toHaveBeenCalledOnce();
|
|
const query = firstCallArgument(projectFindMany) as {
|
|
where: {
|
|
pipelineId: unknown;
|
|
AND: Array<{ OR?: unknown }>;
|
|
};
|
|
orderBy: unknown;
|
|
take: number;
|
|
select: Record<string, unknown>;
|
|
};
|
|
expect(query.where.pipelineId).toBe("pipeline_open");
|
|
expect(query.where.AND).toEqual(
|
|
expect.arrayContaining([
|
|
expect.objectContaining({
|
|
OR: expect.arrayContaining([
|
|
{
|
|
mitglieder: {
|
|
some: {
|
|
tenantId: "tenant_1",
|
|
archivedAt: null,
|
|
OR: [{ userId: "user_1" }, { groupId: { in: ["group_1"] } }],
|
|
},
|
|
},
|
|
},
|
|
]),
|
|
}),
|
|
{ pipelineId: { notIn: ["pipeline_denied"] } },
|
|
])
|
|
);
|
|
expect(tx.projektMitglied.findMany).not.toHaveBeenCalled();
|
|
expect(query.orderBy).toEqual([{ createdAt: "desc" }, { id: "desc" }]);
|
|
expect(query.take).toBe(2);
|
|
expect(query.select).not.toHaveProperty("potenziellerAuftragswert");
|
|
expect(query.select).not.toHaveProperty("auftragsvolumen");
|
|
expect(result.projects).toHaveLength(1);
|
|
expect(result.projects[0]).not.toHaveProperty("valuePotential");
|
|
expect(result.projects[0]).not.toHaveProperty("orderVolume");
|
|
expect(decodeCursor(result.nextCursor)).toEqual({ id: "project_member", createdAt: createdAt.toISOString() });
|
|
});
|
|
|
|
it("loads all contact channels but only relations whose counterpart is visible", async () => {
|
|
const now = new Date("2026-07-12T12:00:00.000Z");
|
|
const contactFindFirst = vi.fn(async () => ({
|
|
id: "company_1",
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
kontaktTyp: "organisation" as const,
|
|
kontaktStatus: "kunde",
|
|
vorname: null,
|
|
nachname: null,
|
|
orgName: "Acme GmbH",
|
|
orgMerkmal: "gmbh",
|
|
primaerEmail: "office@acme.test",
|
|
primaerTelefon: "+49 30 123",
|
|
adresseId: "address_1",
|
|
zustaendigerUserId: "user_1",
|
|
language: "de",
|
|
emails: [
|
|
{ id: "email_1", email: "office@acme.test", primaer: true },
|
|
{ id: "email_2", email: "billing@acme.test", primaer: false },
|
|
],
|
|
telefone: [{ id: "phone_1", telefon: "+49 30 123", primaer: true }],
|
|
relationenVon: [
|
|
{ id: "relation_visible", zuKontaktId: "contact_visible", rolle: "hauptkontakt", kontext: "Visible context" },
|
|
{ id: "relation_hidden", zuKontaktId: "contact_hidden", rolle: "sekundaerkontakt", kontext: "Must not leak" },
|
|
],
|
|
relationenZu: [],
|
|
}));
|
|
const relatedFindMany = vi.fn(async () => [
|
|
{
|
|
id: "contact_visible",
|
|
kontaktTyp: "privatperson" as const,
|
|
vorname: "Ada",
|
|
nachname: "Lovelace",
|
|
orgName: null,
|
|
primaerEmail: "ada@acme.test",
|
|
primaerTelefon: null,
|
|
},
|
|
]);
|
|
const tx = {
|
|
$executeRaw: rlsExecutor(),
|
|
kontakt: { findFirst: contactFindFirst, findMany: relatedFindMany },
|
|
adresse: {
|
|
findFirst: vi.fn(async () => ({ strasse: "Main", hausnummer: "1", plz: "10115", ort: "Berlin", land: "DE" })),
|
|
},
|
|
};
|
|
const ctx = contextWith(tx, ["crm.read_own"]);
|
|
|
|
const result = await getVisibleContactDetail(ctx, "company_1");
|
|
|
|
expect(tx.$executeRaw).toHaveBeenCalledOnce();
|
|
const mainQuery = firstCallArgument(contactFindFirst) as {
|
|
where: Record<string, unknown>;
|
|
select: {
|
|
emails: { take: number };
|
|
telefone: { take: number };
|
|
relationenVon: { take: number };
|
|
relationenZu: { take: number };
|
|
};
|
|
};
|
|
expect(mainQuery.where).toMatchObject({ tenantId: "tenant_1", archivedAt: null });
|
|
expect(mainQuery.where.OR).toEqual([{ zustaendigerUserId: "user_1" }, { createdByUserId: "user_1" }]);
|
|
expect(mainQuery.select.emails.take).toBe(51);
|
|
expect(mainQuery.select.telefone.take).toBe(51);
|
|
expect(mainQuery.select.relationenVon.take).toBe(26);
|
|
expect(mainQuery.select.relationenZu.take).toBe(26);
|
|
const relatedQuery = firstCallArgument(relatedFindMany) as { where: Record<string, unknown> };
|
|
expect(relatedQuery.where).toMatchObject({ archivedAt: null, id: { in: ["contact_visible", "contact_hidden"] } });
|
|
expect(result.contact).toMatchObject({
|
|
id: "company_1",
|
|
type: "company",
|
|
name: "Acme GmbH",
|
|
language: "de",
|
|
emails: [
|
|
{ id: "email_1", value: "office@acme.test", isPrimary: true },
|
|
{ id: "email_2", value: "billing@acme.test", isPrimary: false },
|
|
],
|
|
address: { city: "Berlin", country: "DE" },
|
|
truncated: { emails: false, phones: false, relations: false },
|
|
});
|
|
expect(result.contact.relations).toEqual([
|
|
expect.objectContaining({
|
|
id: "relation_visible",
|
|
direction: "outgoing",
|
|
relatedContact: expect.objectContaining({ id: "contact_visible", type: "contact", name: "Ada Lovelace" }),
|
|
}),
|
|
]);
|
|
expect(JSON.stringify(result)).not.toContain("relation_hidden");
|
|
expect(JSON.stringify(result)).not.toContain("Must not leak");
|
|
});
|
|
|
|
it("caps contact channels and relation fan-out in one detail response", async () => {
|
|
const now = new Date("2026-07-12T12:00:00.000Z");
|
|
const contactFindMany = vi.fn(async () => []);
|
|
const tx = {
|
|
$executeRaw: rlsExecutor(),
|
|
kontakt: {
|
|
findFirst: vi.fn(async () => ({
|
|
id: "company_large",
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
kontaktTyp: "organisation" as const,
|
|
kontaktStatus: "kunde",
|
|
vorname: null,
|
|
nachname: null,
|
|
orgName: "Large GmbH",
|
|
orgMerkmal: "gmbh",
|
|
primaerEmail: "office@large.test",
|
|
primaerTelefon: null,
|
|
adresseId: null,
|
|
zustaendigerUserId: "user_1",
|
|
language: "de",
|
|
emails: Array.from({ length: 101 }, (_, index) => ({ id: `email_${index}`, email: `mail${index}@large.test`, primaer: index === 0 })),
|
|
telefone: Array.from({ length: 101 }, (_, index) => ({ id: `phone_${index}`, telefon: `+49${index}`, primaer: index === 0 })),
|
|
relationenVon: Array.from({ length: 101 }, (_, index) => ({
|
|
id: `relation_${index}`,
|
|
zuKontaktId: `contact_${index}`,
|
|
rolle: "ansprechpartner",
|
|
kontext: null,
|
|
})),
|
|
relationenZu: [],
|
|
})),
|
|
findMany: contactFindMany,
|
|
},
|
|
adresse: { findFirst: vi.fn(async () => null) },
|
|
};
|
|
|
|
const result = await getVisibleContactDetail(contextWith(tx, ["crm.read_own"]), "company_large");
|
|
|
|
expect(result.contact.emails).toHaveLength(50);
|
|
expect(result.contact.phones).toHaveLength(50);
|
|
expect(result.contact.truncated).toEqual({ emails: true, phones: true, relations: true });
|
|
const relatedQuery = firstCallArgument(contactFindMany) as { where: { id: { in: string[] } } };
|
|
expect(relatedQuery.where.id.in).toHaveLength(25);
|
|
});
|
|
|
|
it("checks the contact/company discriminator and never queries activities for a mismatched subject", async () => {
|
|
const activityFindMany = vi.fn(async () => []);
|
|
const tx = {
|
|
$executeRaw: rlsExecutor(),
|
|
kontakt: { findFirst: vi.fn(async () => null) },
|
|
activity: { findMany: activityFindMany },
|
|
};
|
|
const ctx = contextWith(tx, ["crm.read_own"]);
|
|
|
|
await expect(listVisibleActivities(ctx, { subjectType: "company", subjectId: "person_1" })).rejects.toMatchObject({
|
|
status: 404,
|
|
code: "subject_not_found",
|
|
});
|
|
|
|
const subjectQuery = firstCallArgument(tx.kontakt.findFirst) as { where: Record<string, unknown> };
|
|
expect(subjectQuery.where.kontaktTyp).toBe("organisation");
|
|
expect(activityFindMany).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("checks task creator, assignee, watcher and group visibility before loading its activities", async () => {
|
|
const taskFindFirst = vi.fn(async () => ({ id: "task_1" }));
|
|
const activityFindMany = vi.fn(async () => []);
|
|
const tx = {
|
|
$executeRaw: rlsExecutor(),
|
|
groupUser: { findMany: vi.fn(async () => [{ groupId: "group_1" }]) },
|
|
task: { findFirst: taskFindFirst },
|
|
activity: { findMany: activityFindMany },
|
|
};
|
|
const ctx = contextWith(tx, ["tasks.read_own"]);
|
|
|
|
const result = await listVisibleActivities(ctx, { subjectType: "task", subjectId: "task_1" });
|
|
|
|
const subjectQuery = firstCallArgument(taskFindFirst) as { where: { OR: unknown[] } };
|
|
expect(subjectQuery.where.OR).toEqual(
|
|
expect.arrayContaining([
|
|
{ createdByUserId: "user_1" },
|
|
{ assignedToUserId: "user_1" },
|
|
{ watchers: { some: { tenantId: "tenant_1", userId: "user_1" } } },
|
|
{ assignedToGroupId: { in: ["group_1"] } },
|
|
])
|
|
);
|
|
expect(activityFindMany).toHaveBeenCalledOnce();
|
|
expect(result.activities).toEqual([]);
|
|
expect(result.nextCursor).toBeNull();
|
|
});
|
|
|
|
it("masks foreign e-mail summaries and never returns activity metadata or related references", async () => {
|
|
const firstCreatedAt = new Date("2026-07-12T12:00:00.000Z");
|
|
const secondCreatedAt = new Date("2026-07-12T11:00:00.000Z");
|
|
const thirdCreatedAt = new Date("2026-07-12T10:00:00.000Z");
|
|
const activityFindMany = vi.fn(async () => [
|
|
{
|
|
id: "activity_own",
|
|
createdAt: firstCreatedAt,
|
|
actorUserId: "user_1",
|
|
actorKind: "user",
|
|
activityType: "email_sent",
|
|
summaryText: "Visible own-mailbox subject",
|
|
metadata: { mailboxId: "mailbox_own", secret: "never-return" },
|
|
relatedEntityRefs: [{ type: "lead", id: "lead_secret" }],
|
|
},
|
|
{
|
|
id: "activity_foreign",
|
|
createdAt: secondCreatedAt,
|
|
actorUserId: "user_2",
|
|
actorKind: "user",
|
|
activityType: "email_sent",
|
|
summaryText: "Foreign mailbox subject must not leak",
|
|
metadata: { mailboxId: "mailbox_foreign", secret: "never-return" },
|
|
},
|
|
{
|
|
id: "activity_next",
|
|
createdAt: thirdCreatedAt,
|
|
actorUserId: null,
|
|
actorKind: "system",
|
|
activityType: "note_added",
|
|
summaryText: "Next page",
|
|
metadata: null,
|
|
},
|
|
]);
|
|
const tx = {
|
|
$executeRaw: rlsExecutor(),
|
|
kontakt: { findFirst: vi.fn(async () => ({ id: "company_1" })) },
|
|
activity: { findMany: activityFindMany },
|
|
emailIntegrationMailbox: { findMany: vi.fn(async () => [{ id: "mailbox_own" }]) },
|
|
};
|
|
const ctx = contextWith(tx, ["crm.read_own", "email.read_own"]);
|
|
|
|
const result = await listVisibleActivities(ctx, {
|
|
subjectType: "company",
|
|
subjectId: "company_1",
|
|
activityType: "email_sent",
|
|
limit: 2,
|
|
});
|
|
|
|
expect(tx.$executeRaw).toHaveBeenCalledOnce();
|
|
const activityQuery = firstCallArgument(activityFindMany) as {
|
|
where: Record<string, unknown>;
|
|
orderBy: unknown;
|
|
take: number;
|
|
select: Record<string, unknown>;
|
|
};
|
|
expect(activityQuery.where).toMatchObject({
|
|
tenantId: "tenant_1",
|
|
subjectType: "company",
|
|
subjectId: "company_1",
|
|
activityType: "email_sent",
|
|
});
|
|
expect(activityQuery.orderBy).toEqual([{ createdAt: "desc" }, { id: "desc" }]);
|
|
expect(activityQuery.take).toBe(3);
|
|
expect(activityQuery.select).not.toHaveProperty("relatedEntityRefs");
|
|
expect(result.activities).toEqual([
|
|
expect.objectContaining({
|
|
id: "activity_own",
|
|
summaryText: "Visible own-mailbox subject",
|
|
summaryTextTruncated: false,
|
|
summaryTextIsUntrustedData: true,
|
|
}),
|
|
expect.objectContaining({
|
|
id: "activity_foreign",
|
|
summaryText: "Email activity is not visible to this user.",
|
|
summaryTextTruncated: false,
|
|
summaryTextIsUntrustedData: true,
|
|
}),
|
|
]);
|
|
expect(decodeCursor(result.nextCursor)).toEqual({ id: "activity_foreign", createdAt: secondCreatedAt.toISOString() });
|
|
const serialized = JSON.stringify(result);
|
|
expect(serialized).not.toContain("mailbox_own");
|
|
expect(serialized).not.toContain("mailbox_foreign");
|
|
expect(serialized).not.toContain("never-return");
|
|
expect(serialized).not.toContain("lead_secret");
|
|
expect(serialized).not.toContain("Foreign mailbox subject must not leak");
|
|
});
|
|
});
|