196 lines
7.2 KiB
TypeScript
196 lines
7.2 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
|
|
import { describe, expect, it, vi } from "vitest";
|
|
|
|
import {
|
|
buildSeedFileObjectMetadata,
|
|
buildSeedPdfBytes,
|
|
deleteDemoProSeedFileObjects,
|
|
deleteDemoProTenantFileObjects,
|
|
seedFileStorageKey,
|
|
seedFileStoragePrefix,
|
|
uploadDemoProSeedFileObjects,
|
|
verifyDemoProSeedFileObjects,
|
|
} from "./file-objects";
|
|
|
|
const descriptor = {
|
|
id: "rheinmain-shk-v1-file-0001",
|
|
displayName: "Aufmaß_HG-2026-0042.pdf",
|
|
notes: "Projektunterlage zur Wärmepumpenmodernisierung; dem Projekt HG-2026-0042 zugeordnet.",
|
|
};
|
|
|
|
describe("demo-pro seed file objects", () => {
|
|
it("builds a deterministic PDF with valid xref offsets and exact metadata", () => {
|
|
const bytes = buildSeedPdfBytes(descriptor);
|
|
const second = buildSeedPdfBytes(descriptor);
|
|
const pdf = new TextDecoder().decode(bytes);
|
|
|
|
expect(second).toEqual(bytes);
|
|
expect(pdf.startsWith("%PDF-1.4\n")).toBe(true);
|
|
expect(pdf.endsWith("%%EOF\n")).toBe(true);
|
|
|
|
const startXref = Number(pdf.match(/startxref\n(\d+)\n%%EOF/u)?.[1]);
|
|
expect(pdf.slice(startXref).startsWith("xref\n")).toBe(true);
|
|
const xrefEntries = [...pdf.matchAll(/^(\d{10}) 00000 n $/gmu)].map((match) => Number(match[1]));
|
|
expect(xrefEntries).toHaveLength(5);
|
|
for (const [index, offset] of xrefEntries.entries()) {
|
|
expect(pdf.slice(offset).startsWith(`${index + 1} 0 obj\n`)).toBe(true);
|
|
}
|
|
|
|
const metadata = buildSeedFileObjectMetadata(descriptor);
|
|
expect(metadata.mimeType).toBe("application/pdf");
|
|
expect(metadata.sizeBytes).toBe(bytes.byteLength);
|
|
expect(metadata.checksumSha256).toBe(createHash("sha256").update(bytes).digest("hex"));
|
|
});
|
|
|
|
it("uses the mandatory tenant-prefixed Files storage path", () => {
|
|
expect(seedFileStorageKey("tenant-staging", descriptor.id)).toBe(`tenants/tenant-staging/files/${descriptor.id}/original`);
|
|
expect(seedFileStoragePrefix("tenant-staging")).toBe("tenants/tenant-staging/files/");
|
|
expect(() => seedFileStorageKey("tenant/foreign", descriptor.id)).toThrow(/Invalid storage path segment/u);
|
|
});
|
|
|
|
it("uploads all PDFs with bounded concurrency and fails on metadata drift", async () => {
|
|
const files = Array.from({ length: 9 }, (_, index) =>
|
|
buildSeedFileObjectMetadata({ ...descriptor, id: `${descriptor.id}-${index}`, displayName: `Dokument-${index}.pdf` })
|
|
);
|
|
let active = 0;
|
|
let maxActive = 0;
|
|
const putObject = vi.fn(async ({ body }: { body: Uint8Array }) => {
|
|
active += 1;
|
|
maxActive = Math.max(maxActive, active);
|
|
expect(new TextDecoder().decode(body)).toMatch(/^%PDF-1\.4/u);
|
|
await Promise.resolve();
|
|
active -= 1;
|
|
});
|
|
|
|
await expect(uploadDemoProSeedFileObjects({ tenantId: "tenant-staging", files, concurrency: 3, bucket: "staging-files", putObject })).resolves.toEqual({
|
|
bucket: "staging-files",
|
|
uploaded: files.length,
|
|
});
|
|
expect(putObject).toHaveBeenCalledTimes(files.length);
|
|
expect(maxActive).toBeLessThanOrEqual(3);
|
|
expect(putObject.mock.calls[0]![0]).toMatchObject({
|
|
bucket: "staging-files",
|
|
key: `tenants/tenant-staging/files/${descriptor.id}-0/original`,
|
|
contentType: "application/pdf",
|
|
});
|
|
|
|
await expect(
|
|
uploadDemoProSeedFileObjects({
|
|
tenantId: "tenant-staging",
|
|
files: [{ ...files[0]!, sizeBytes: files[0]!.sizeBytes + 1 }],
|
|
bucket: "staging-files",
|
|
putObject,
|
|
})
|
|
).rejects.toThrow(/metadata drifted/u);
|
|
});
|
|
|
|
it("deletes every deterministic object and refuses cleanup without storage", async () => {
|
|
const files = [{ id: "file-1" }, { id: "file-2" }];
|
|
const deleteObject = vi.fn(async () => undefined);
|
|
await expect(
|
|
deleteDemoProSeedFileObjects({
|
|
tenantId: "tenant-staging",
|
|
files,
|
|
concurrency: 2,
|
|
bucket: "staging-files",
|
|
deleteObject,
|
|
storageConfigured: () => true,
|
|
})
|
|
).resolves.toEqual({ bucket: "staging-files", deleted: 2 });
|
|
expect(deleteObject).toHaveBeenCalledTimes(2);
|
|
|
|
await expect(
|
|
deleteDemoProSeedFileObjects({
|
|
tenantId: "tenant-staging",
|
|
files,
|
|
bucket: "staging-files",
|
|
deleteObject,
|
|
storageConfigured: () => false,
|
|
})
|
|
).rejects.toThrow(/storage provider is not configured/u);
|
|
});
|
|
|
|
it("downloads and verifies every uploaded object against its exact checksum", async () => {
|
|
const file = buildSeedFileObjectMetadata(descriptor);
|
|
const bytes = buildSeedPdfBytes(file);
|
|
let storedBytes = bytes;
|
|
const send = vi.fn(async (command: unknown) => {
|
|
if ((command as { constructor: { name: string } }).constructor.name === "ListObjectsV2Command") {
|
|
return { Contents: [{ Key: seedFileStorageKey("tenant-staging", file.id) }], IsTruncated: false };
|
|
}
|
|
return {
|
|
ContentLength: storedBytes.byteLength,
|
|
Body: { transformToByteArray: async () => storedBytes },
|
|
};
|
|
});
|
|
|
|
await expect(
|
|
verifyDemoProSeedFileObjects({
|
|
tenantId: "tenant-staging",
|
|
files: [file],
|
|
bucket: "staging-files",
|
|
client: { send },
|
|
})
|
|
).resolves.toEqual({ bucket: "staging-files", verified: 1 });
|
|
expect(send.mock.calls.map(([command]) => command.constructor.name)).toEqual(["ListObjectsV2Command", "GetObjectCommand"]);
|
|
|
|
const corrupted = new Uint8Array(bytes);
|
|
corrupted[20] = corrupted[20]! ^ 1;
|
|
storedBytes = corrupted;
|
|
await expect(
|
|
verifyDemoProSeedFileObjects({
|
|
tenantId: "tenant-staging",
|
|
files: [file],
|
|
bucket: "staging-files",
|
|
client: { send },
|
|
})
|
|
).rejects.toThrow(/metadata drifted/u);
|
|
});
|
|
|
|
it("fails verification when the managed prefix contains an extra object", async () => {
|
|
const file = buildSeedFileObjectMetadata(descriptor);
|
|
const send = vi.fn(async () => ({
|
|
Contents: [{ Key: seedFileStorageKey("tenant-staging", file.id) }, { Key: "tenants/tenant-staging/files/orphan/original" }],
|
|
IsTruncated: false,
|
|
}));
|
|
|
|
await expect(
|
|
verifyDemoProSeedFileObjects({
|
|
tenantId: "tenant-staging",
|
|
files: [file],
|
|
bucket: "staging-files",
|
|
client: { send },
|
|
})
|
|
).rejects.toThrow(/unexpected storage object/u);
|
|
});
|
|
|
|
it("removes every object below the managed tenant file prefix", async () => {
|
|
const send = vi
|
|
.fn()
|
|
.mockResolvedValueOnce({
|
|
Contents: [{ Key: "tenants/tenant-staging/files/file-1/original" }, { Key: "tenants/tenant-staging/files/orphan/thumb.webp" }],
|
|
IsTruncated: true,
|
|
})
|
|
.mockResolvedValueOnce({ Errors: [] })
|
|
.mockResolvedValueOnce({
|
|
Contents: [{ Key: "tenants/tenant-staging/files/file-3/original" }],
|
|
IsTruncated: false,
|
|
})
|
|
.mockResolvedValueOnce({ Errors: [] })
|
|
.mockResolvedValueOnce({ Contents: [], IsTruncated: false });
|
|
|
|
await expect(deleteDemoProTenantFileObjects({ tenantId: "tenant-staging", bucket: "staging-files", client: { send } })).resolves.toEqual({
|
|
bucket: "staging-files",
|
|
deleted: 3,
|
|
});
|
|
expect(send.mock.calls.map(([command]) => command.constructor.name)).toEqual([
|
|
"ListObjectsV2Command",
|
|
"DeleteObjectsCommand",
|
|
"ListObjectsV2Command",
|
|
"DeleteObjectsCommand",
|
|
"ListObjectsV2Command",
|
|
]);
|
|
});
|
|
});
|