// @vitest-environment node import { beforeEach, describe, expect, it, vi } from "vitest"; import { loader } from "./audit-trails"; import { getAdminAuditLogList, serializeAdminAuditLogsCsv } from "@toolctrl/db/logs.server"; import { getTranslations } from "~/locale/i18next.server"; import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService"; import { readRepoFile } from "~/utils/testing/repoPaths"; vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }), })); vi.mock("react-router", async () => { const actual = await vi.importActual("react-router"); return { ...actual, Link: () => null, useLoaderData: () => ({}), }; }); vi.mock("~/components/app/events/LogsTable", () => ({ default: () => null })); vi.mock("~/components/ui/input/InputFilters", () => ({ default: () => null })); vi.mock("~/components/ui/layouts/IndexPageLayout", () => ({ default: () => null })); vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(), })); vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn(), })); vi.mock("@toolctrl/db/logs.server", () => ({ getAdminAuditLogList: vi.fn(), serializeAdminAuditLogsCsv: vi.fn(), })); const auditRows = [ { id: "log-1", createdAt: new Date("2026-05-08T10:00:00.000Z"), tenantId: "tenant-1", userId: "user-1", apiKeyId: null, action: "create", url: "/acme/contacts", details: "redacted details", rowId: null, commentId: null, tenant: { id: "tenant-1", name: "Acme", slug: "acme" }, user: { id: "user-1", email: "admin@example.test", firstName: "Ada", lastName: "Admin" }, apiKey: null, comment: null, }, ]; function callLoader(url: string) { const request = new Request(url); return loader({ request, params: {}, context: {}, unstable_pattern: "admin/audit-trails" }); } function readAuditRoute() { return readRepoFile("apps/web/app/routes/admin/audit-trails.tsx"); } describe("admin audit trails route", () => { beforeEach(() => { vi.clearAllMocks(); process.env.APP_NAME = "ToolCTRL"; vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never); vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never); vi.mocked(getAdminAuditLogList).mockResolvedValue({ rows: auditRows, total: 1, take: 25, skip: 25 } as never); vi.mocked(serializeAdminAuditLogsCsv).mockReturnValue("csv-body\n"); }); it("checks permission before reading the filtered table data", async () => { const data = await callLoader( "https://admin.example.test/audit-trails?q=contact&action=create&url=%2Fcontacts&tenantId=tenant-1&userId=user-1&createdAtFrom=2026-05-01&createdAtTo=2026-05-08&page=2&pageSize=25", ); expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.auditTrails.view"); expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getAdminAuditLogList).mock.invocationCallOrder[0]); expect(getAdminAuditLogList).toHaveBeenCalledWith({ q: "contact", action: "create", url: "/contacts", tenantId: "tenant-1", userId: "user-1", createdAtFrom: "2026-05-01", createdAtTo: "2026-05-08", take: 25, skip: 25, }); expect(data).toMatchObject({ title: "translated:models.log.plural | ToolCTRL", items: auditRows, pagination: { page: 2, pageSize: 25, totalItems: 1, totalPages: 1 }, }); }); it("exports CSV with the same filters and a capped export window after permission passes", async () => { const response = (await callLoader( "https://admin.example.test/audit-trails?export=csv&q=login&action=auth&url=%2Flogin&tenantId=tenant-2&userId=user-2&createdAtFrom=bad-date&createdAtTo=2026-05-08", )) as Response; expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.auditTrails.view"); expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getAdminAuditLogList).mock.invocationCallOrder[0]); expect(getAdminAuditLogList).toHaveBeenCalledWith({ q: "login", action: "auth", url: "/login", tenantId: "tenant-2", userId: "user-2", createdAtFrom: "bad-date", createdAtTo: "2026-05-08", take: 500, skip: 0, }); expect(vi.mocked(getAdminAuditLogList).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(serializeAdminAuditLogsCsv).mock.invocationCallOrder[0]); expect(serializeAdminAuditLogsCsv).toHaveBeenCalledWith(auditRows); expect(response.headers.get("Content-Type")).toBe("text/csv; charset=utf-8"); expect(response.headers.get("Content-Disposition")).toBe('attachment; filename="admin-audit-logs.csv"'); expect(await response.text()).toBe("csv-body\n"); }); it("rejects table loads without permission before helper calls", async () => { const rejection = new Response("Forbidden", { status: 403 }); vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never); await expect( callLoader( "https://admin.example.test/audit-trails?q=contact&action=create&url=%2Fcontacts&tenantId=tenant-1&userId=user-1&createdAtFrom=2026-05-01&createdAtTo=2026-05-08", ), ).rejects.toBe(rejection); expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.auditTrails.view"); expect(getAdminAuditLogList).not.toHaveBeenCalled(); expect(serializeAdminAuditLogsCsv).not.toHaveBeenCalled(); }); it("rejects CSV export without permission before helper calls", async () => { const rejection = new Response("Forbidden", { status: 403 }); vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never); await expect( callLoader( "https://admin.example.test/audit-trails?export=csv&q=login&action=auth&url=%2Flogin&tenantId=tenant-2&userId=user-2&createdAtFrom=2026-05-01&createdAtTo=2026-05-08", ), ).rejects.toBe(rejection); expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.auditTrails.view"); expect(getAdminAuditLogList).not.toHaveBeenCalled(); expect(serializeAdminAuditLogsCsv).not.toHaveBeenCalled(); }); it("does not crash on malformed numeric and date filters", async () => { vi.mocked(getAdminAuditLogList).mockResolvedValue({ rows: [], total: 0, take: 10, skip: 0 } as never); const data = await callLoader("https://admin.example.test/audit-trails?page=abc&pageSize=-5&createdAtFrom=not-a-date&createdAtTo=also-bad"); expect(getAdminAuditLogList).toHaveBeenCalledWith({ q: null, action: null, url: null, tenantId: null, userId: null, createdAtFrom: "not-a-date", createdAtTo: "also-bad", take: 10, skip: 0, }); expect(data).toMatchObject({ pagination: { page: 1, pageSize: 10, totalItems: 0, totalPages: 0 } }); }); it("uses the package audit-log boundary instead of the legacy app DB helper", () => { const source = readAuditRoute(); expect(source).toContain('from "@toolctrl/db/logs.server"'); expect(source).toContain("getAdminAuditLogList"); expect(source).toContain("serializeAdminAuditLogsCsv"); expect(source).not.toContain("getAllLogs"); expect(source).not.toContain('from "~/utils/db/logs.db.server"'); }); });