Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/db/src/logs.server.test.ts
T

240 lines
8.1 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import {
buildAuditLogWhereFromFilters,
getAdminAuditLogList,
getTenantAuditLogList,
redactLogDetails,
serializeAdminAuditLogsCsv,
type AdminAuditLogClient,
type AdminAuditLogRow,
} from "./logs.server.js";
describe("admin audit log list filters", () => {
it("builds focused where input from supported filters", () => {
const where = buildAuditLogWhereFromFilters({
q: " contact ",
action: "update",
url: "/api/contacts",
tenantId: "tenant_1",
userId: "user_1",
createdAtFrom: "2024-01-02T00:00:00.000Z",
createdAtTo: "2024-01-03T00:00:00.000Z",
});
expect(where).toEqual({
action: "update",
url: { contains: "/api/contacts", mode: "insensitive" },
tenantId: "tenant_1",
userId: "user_1",
createdAt: {
gte: new Date("2024-01-02T00:00:00.000Z"),
lte: new Date("2024-01-03T00:00:00.000Z"),
},
AND: [
{
OR: [
{ action: { contains: "contact", mode: "insensitive" } },
{ url: { contains: "contact", mode: "insensitive" } },
{ details: { contains: "contact", mode: "insensitive" } },
{ tenantId: { contains: "contact", mode: "insensitive" } },
{ userId: { contains: "contact", mode: "insensitive" } },
],
},
],
});
});
it("ignores malformed date filters", () => {
expect(buildAuditLogWhereFromFilters({ createdAtFrom: "not-a-date", createdAtTo: "2024-01-03T00:00:00.000Z" })).toEqual({
createdAt: { lte: new Date("2024-01-03T00:00:00.000Z") },
});
expect(buildAuditLogWhereFromFilters({ createdAtFrom: "not-a-date", createdAtTo: "still-not-a-date" })).toEqual({});
});
it("queries newest first with bounded pagination and shared where input", async () => {
const rows = [makeAuditRow({ id: "log_1" })];
const client: AdminAuditLogClient = {
log: {
findMany: vi.fn().mockResolvedValue(rows),
count: vi.fn().mockResolvedValue(7),
},
} as unknown as AdminAuditLogClient;
await expect(
getAdminAuditLogList({ action: "create", take: 999, skip: 2, createdAtFrom: "bad-date" }, client),
).resolves.toEqual({ rows, total: 7, take: 500, skip: 2 });
expect(client.log.findMany).toHaveBeenCalledWith({
where: { action: "create" },
include: {
user: { select: { id: true, email: true, firstName: true, lastName: true } },
tenant: { select: { id: true, name: true, slug: true } },
apiKey: { select: { id: true, alias: true } },
},
orderBy: { createdAt: "desc" },
take: 500,
skip: 2,
});
expect(client.log.count).toHaveBeenCalledWith({ where: { action: "create" } });
});
});
describe("tenant audit log list filters", () => {
it("forces tenant scoping while composing supported filters", async () => {
const rows = [makeAuditRow({ id: "log_1" })];
const client: AdminAuditLogClient = {
log: {
findMany: vi.fn().mockResolvedValue(rows),
count: vi.fn().mockResolvedValue(3),
},
} as unknown as AdminAuditLogClient;
await expect(
getTenantAuditLogList(
"tenant_forced",
{
q: " contact ",
action: "update",
url: "/api/contacts",
userId: "user_1",
createdAtFrom: "2024-01-02T00:00:00.000Z",
createdAtTo: "2024-01-03T00:00:00.000Z",
take: 25,
skip: 5,
},
client,
),
).resolves.toEqual({ rows, total: 3, take: 25, skip: 5 });
const where = {
action: "update",
url: { contains: "/api/contacts", mode: "insensitive" },
tenantId: "tenant_forced",
userId: "user_1",
createdAt: {
gte: new Date("2024-01-02T00:00:00.000Z"),
lte: new Date("2024-01-03T00:00:00.000Z"),
},
AND: [
{
OR: [
{ action: { contains: "contact", mode: "insensitive" } },
{ url: { contains: "contact", mode: "insensitive" } },
{ details: { contains: "contact", mode: "insensitive" } },
{ tenantId: { contains: "contact", mode: "insensitive" } },
{ userId: { contains: "contact", mode: "insensitive" } },
],
},
],
};
expect(client.log.findMany).toHaveBeenCalledWith({
where,
include: {
user: { select: { id: true, email: true, firstName: true, lastName: true } },
tenant: { select: { id: true, name: true, slug: true } },
apiKey: { select: { id: true, alias: true } },
},
orderBy: { createdAt: "desc" },
take: 25,
skip: 5,
});
expect(client.log.count).toHaveBeenCalledWith({ where });
});
it("ignores caller-provided tenant overrides and bounds pagination", async () => {
const client: AdminAuditLogClient = {
log: {
findMany: vi.fn().mockResolvedValue([]),
count: vi.fn().mockResolvedValue(0),
},
} as unknown as AdminAuditLogClient;
await expect(
getTenantAuditLogList("tenant_forced", { tenantId: "tenant_other", take: 9999, skip: -10, createdAtFrom: "bad-date", createdAtTo: "also-bad" }, client),
).resolves.toEqual({ rows: [], total: 0, take: 500, skip: 0 });
expect(client.log.findMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_forced" },
include: {
user: { select: { id: true, email: true, firstName: true, lastName: true } },
tenant: { select: { id: true, name: true, slug: true } },
apiKey: { select: { id: true, alias: true } },
},
orderBy: { createdAt: "desc" },
take: 500,
skip: 0,
});
expect(client.log.count).toHaveBeenCalledWith({ where: { tenantId: "tenant_forced" } });
});
});
describe("serializeAdminAuditLogsCsv", () => {
it("serializes stable headers and empty optional relations without crashing", () => {
expect(
serializeAdminAuditLogsCsv([
makeAuditRow({
createdAt: new Date("2024-01-02T03:04:05.000Z"),
tenantId: null,
userId: null,
apiKeyId: null,
tenant: null,
user: null,
apiKey: null,
details: null,
}),
]),
).toBe(
'"Created At","Tenant","Actor","Actor Type","Action","URL","Details"\n"2024-01-02T03:04:05.000Z","","System","System","create","/api/contacts",""\n',
);
});
it("quotes commas, quotes, newlines, and formula-like values as text", () => {
const csv = serializeAdminAuditLogsCsv([
makeAuditRow({
createdAt: new Date("2024-01-02T03:04:05.000Z"),
action: "=cmd",
url: "/api/contacts,one",
details: 'Changed "field"\nnext line',
tenant: { id: "tenant_1", name: " +Tenant", slug: "tenant" },
user: { id: "user_1", email: "ada@example.com", firstName: "Ada", lastName: "Lovelace" },
}),
]);
expect(csv).toBe(
'"Created At","Tenant","Actor","Actor Type","Action","URL","Details"\n"2024-01-02T03:04:05.000Z","\' +Tenant","Ada Lovelace <ada@example.com>","User","\'=cmd","/api/contacts,one","Changed ""field""\nnext line"\n',
);
});
it("redacts sensitive details before CSV export", () => {
const csv = serializeAdminAuditLogsCsv([
makeAuditRow({ details: JSON.stringify({ token: "secret-token", kept: "value" }) }),
]);
expect(csv).toContain('"{""token"":""[REDACTED]"",""kept"":""value""}"');
expect(csv).not.toContain("secret-token");
});
it("exports detail redaction for UI display paths", () => {
expect(redactLogDetails("token=secret-token Authorization=Bearer secret")).toBe("token=[REDACTED] Authorization=Bearer [REDACTED]");
});
});
function makeAuditRow(overrides: Partial<AdminAuditLogRow> = {}): AdminAuditLogRow {
return {
id: "log_1",
createdAt: new Date("2024-01-01T00:00:00.000Z"),
tenantId: "tenant_1",
userId: "user_1",
apiKeyId: null,
url: "/api/contacts",
action: "create",
details: "Created contact",
tenant: { id: "tenant_1", name: "Tenant One", slug: "tenant-one" },
user: { id: "user_1", email: "user@example.com", firstName: "User", lastName: "One" },
apiKey: null,
...overrides,
};
}