forked from Yara724/api
77 lines
2.7 KiB
TypeScript
77 lines
2.7 KiB
TypeScript
import { mkdtemp, mkdir, rm, symlink, writeFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import { join, resolve } from "node:path";
|
|
import { EstimateImages } from "./estimate-images";
|
|
|
|
describe("managed price estimation image bytes", () => {
|
|
let root: string;
|
|
let uploads: string;
|
|
const loader = new EstimateImages();
|
|
const png = Buffer.from(
|
|
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a1ioAAAAASUVORK5CYII=",
|
|
"base64",
|
|
);
|
|
const photo = (path: string) => ({
|
|
path,
|
|
photoKey: "photo:0",
|
|
label: "bumper",
|
|
partKey: "outer:0",
|
|
kind: "damage" as const,
|
|
});
|
|
beforeEach(async () => {
|
|
root = await mkdtemp(join(tmpdir(), "price-estimate-images-"));
|
|
await mkdir(resolve("files"), { recursive: true });
|
|
uploads = await mkdtemp(join(resolve("files"), "price-estimate-test-"));
|
|
});
|
|
afterEach(async () => {
|
|
await rm(uploads, { recursive: true, force: true });
|
|
await rm(root, { recursive: true, force: true });
|
|
});
|
|
|
|
it("uses magic bytes rather than filenames, preserves exact bytes and hashes the source", async () => {
|
|
await writeFile(join(uploads, "photo.jpg"), png);
|
|
const image = await loader.read(photo(join(uploads, "photo.jpg")));
|
|
expect(image.buffer).toEqual(png);
|
|
expect(image.mime).toBe("image/png");
|
|
expect(image.sha256).toMatch(/^[a-f0-9]{64}$/);
|
|
await writeFile(
|
|
join(uploads, "photo.jpg"),
|
|
Buffer.concat([png, Buffer.from("changed")]),
|
|
);
|
|
await expect(
|
|
loader.read({
|
|
...photo(join(uploads, "photo.jpg")),
|
|
sha256: image.sha256,
|
|
}),
|
|
).rejects.toThrow("IMAGE_CHANGED");
|
|
});
|
|
it("rejects paths and symlinks outside managed uploads without reading their contents", async () => {
|
|
const outside = join(root, "private.bin");
|
|
await writeFile(outside, png);
|
|
await symlink(outside, join(uploads, "linked.jpg"));
|
|
await expect(loader.read(photo(outside))).rejects.toThrow(
|
|
"UNAVAILABLE_IMAGE",
|
|
);
|
|
await expect(
|
|
loader.read(photo(join(uploads, "linked.jpg"))),
|
|
).rejects.toThrow("UNAVAILABLE_IMAGE");
|
|
await expect(
|
|
loader.read(photo("https://example.com/image.jpg")),
|
|
).rejects.toThrow("UNAVAILABLE_IMAGE");
|
|
});
|
|
it("rejects unsupported/oversized/missing files with sanitized errors", async () => {
|
|
await writeFile(
|
|
join(uploads, "not-image.jpg"),
|
|
"not an image nor a signature",
|
|
);
|
|
await writeFile(
|
|
join(uploads, "huge.png"),
|
|
Buffer.alloc(10 * 1024 * 1024 + 1),
|
|
);
|
|
for (const file of ["not-image.jpg", "huge.png", "missing.jpg"])
|
|
await expect(loader.read(photo(join(uploads, file)))).rejects.toThrow(
|
|
"UNAVAILABLE_IMAGE",
|
|
);
|
|
});
|
|
});
|