Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+52
@@ -0,0 +1,52 @@
|
||||
// @vitest-environment node
|
||||
import { Buffer } from "node:buffer";
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
// Mirror of clamav-default-client.test.ts but for the CommonJS-interop shape
|
||||
// where `clamscan` exposes `init` directly on the module object with NO default
|
||||
// export. This exercises the `?? mod` fallback and the non-constructor branch
|
||||
// of defaultInitClient (`typeof Factory === "function" ? new ... : Factory`).
|
||||
const ping = vi.fn(async () => "PONG");
|
||||
const scanBuffer = vi.fn(async () => ({ isInfected: false as boolean, viruses: [] as string[] }));
|
||||
const scanStream = vi.fn(async () => ({ isInfected: false as boolean, viruses: [] as string[] }));
|
||||
const init = vi.fn(async () => ({ ping, scanBuffer, scanStream }));
|
||||
|
||||
// `default: undefined` keeps the property declared (so the source's `.default`
|
||||
// access is legal under vitest's strict ESM namespace) while still being
|
||||
// nullish, which forces the `?? mod` fallback and the non-constructor branch.
|
||||
vi.mock("clamscan", () => ({ default: undefined, init }));
|
||||
|
||||
import { createClamAVStorageScanner } from "./clamav-scanner.js";
|
||||
|
||||
const baseConfig = { host: "clamav", port: 3310, timeoutMs: 30000 };
|
||||
|
||||
describe("ClamAVStorageScanner with a default-less clamscan module", () => {
|
||||
test("uses the module object itself as the factory when there is no default export", async () => {
|
||||
const scanner = createClamAVStorageScanner({
|
||||
...baseConfig,
|
||||
loadObject: async () => Buffer.from("hello"),
|
||||
});
|
||||
|
||||
const result = await scanner.scanObject({ bucket: "uploads", key: "a.txt" });
|
||||
|
||||
expect(result.verdict).toBe("clean");
|
||||
// init() is called directly on the module export, never via `new`.
|
||||
expect(init).toHaveBeenCalledTimes(1);
|
||||
expect(ping).toHaveBeenCalled();
|
||||
expect(scanBuffer).toHaveBeenCalledWith(Buffer.from("hello"));
|
||||
});
|
||||
|
||||
test("reuses the cached client across scans (init runs once per scanner)", async () => {
|
||||
const before = init.mock.calls.length;
|
||||
const scanner = createClamAVStorageScanner({
|
||||
...baseConfig,
|
||||
loadObject: async () => Buffer.from("again"),
|
||||
});
|
||||
|
||||
await scanner.scanObject({ bucket: "uploads", key: "b.txt" });
|
||||
await scanner.scanObject({ bucket: "uploads", key: "c.txt" });
|
||||
|
||||
// The per-scanner client cache means two scans trigger exactly one init.
|
||||
expect(init.mock.calls.length - before).toBe(1);
|
||||
});
|
||||
});
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
// @vitest-environment node
|
||||
import { Buffer } from "node:buffer";
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
// Exercises the production defaultInitClient path (no initClient override) by
|
||||
// mocking the lazily-imported `clamscan` package. The factory exposes init(),
|
||||
// which returns the ping/scanBuffer/scanStream surface the wrapper adapts.
|
||||
const ping = vi.fn(async () => "PONG");
|
||||
const scanBuffer = vi.fn(async () => ({ isInfected: false as boolean, viruses: [] as string[] }));
|
||||
const scanStream = vi.fn(async () => ({ isInfected: false as boolean, viruses: [] as string[] }));
|
||||
const init = vi.fn(async () => ({ ping, scanBuffer, scanStream }));
|
||||
|
||||
vi.mock("clamscan", () => {
|
||||
class NodeClam {
|
||||
init = init;
|
||||
}
|
||||
return { default: NodeClam };
|
||||
});
|
||||
|
||||
import { createClamAVStorageScanner } from "./clamav-scanner.js";
|
||||
|
||||
const baseConfig = { host: "clamav", port: 3310, timeoutMs: 30000 };
|
||||
|
||||
describe("ClamAVStorageScanner with the real (mocked) clamscan client", () => {
|
||||
test("initializes the clamscan factory and reports clean for a buffer payload", async () => {
|
||||
const scanner = createClamAVStorageScanner({
|
||||
...baseConfig,
|
||||
loadObject: async () => Buffer.from("hello world"),
|
||||
});
|
||||
|
||||
const result = await scanner.scanObject({ bucket: "uploads", key: "a.txt" });
|
||||
|
||||
expect(result.verdict).toBe("clean");
|
||||
expect(init).toHaveBeenCalledTimes(1);
|
||||
expect(ping).toHaveBeenCalled();
|
||||
expect(scanBuffer).toHaveBeenCalledWith(Buffer.from("hello world"));
|
||||
});
|
||||
|
||||
test("adapts an infected scanBuffer verdict into the scanner result", async () => {
|
||||
scanBuffer.mockResolvedValueOnce({ isInfected: true, viruses: ["Win.Test.EICAR_HDB-1"] });
|
||||
const scanner = createClamAVStorageScanner({
|
||||
...baseConfig,
|
||||
loadObject: async () => Buffer.from("infected"),
|
||||
});
|
||||
|
||||
const result = await scanner.scanObject({ bucket: "uploads", key: "eicar.txt" });
|
||||
expect(result.verdict).toBe("infected");
|
||||
if (result.verdict === "infected") expect(result.signature).toBe("Win.Test.EICAR_HDB-1");
|
||||
});
|
||||
|
||||
test("routes a stream payload through scanStream", async () => {
|
||||
const { Readable } = await import("node:stream");
|
||||
const stream = Readable.from([Buffer.from("payload")]);
|
||||
const scanner = createClamAVStorageScanner({
|
||||
...baseConfig,
|
||||
loadObject: async () => stream,
|
||||
});
|
||||
|
||||
const result = await scanner.scanObject({ bucket: "uploads", key: "s.bin" });
|
||||
expect(result.verdict).toBe("clean");
|
||||
expect(scanStream).toHaveBeenCalledWith(stream);
|
||||
});
|
||||
});
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createStorageScanService,
|
||||
type StorageQuarantineAdapter,
|
||||
type StorageScanner,
|
||||
} from "./index.js";
|
||||
|
||||
const fixedNow = new Date("2026-02-03T04:05:06.000Z");
|
||||
|
||||
function createService(overrides: {
|
||||
scanner?: StorageScanner;
|
||||
quarantine?: StorageQuarantineAdapter;
|
||||
} = {}) {
|
||||
return createStorageScanService({
|
||||
scanner: overrides.scanner ?? {
|
||||
scanObject: vi.fn().mockResolvedValue({ verdict: "clean" }),
|
||||
},
|
||||
quarantine: overrides.quarantine,
|
||||
now: () => fixedNow,
|
||||
});
|
||||
}
|
||||
|
||||
describe("createStorageScanService infected without a quarantine adapter", () => {
|
||||
it("falls back to the scanner-supplied quarantineKey when no adapter ran", async () => {
|
||||
const service = createService({
|
||||
scanner: {
|
||||
scanObject: vi.fn().mockResolvedValue({
|
||||
verdict: "infected",
|
||||
engine: "clamav-1.4",
|
||||
signature: "Eicar-Test-Signature",
|
||||
quarantineKey: "quarantine/uploads/avatar.png",
|
||||
}),
|
||||
},
|
||||
// No quarantine adapter configured at all.
|
||||
});
|
||||
|
||||
const result = await service.scanObject({ bucket: "uploads", key: "avatar.png" });
|
||||
|
||||
expect(result).toEqual({
|
||||
verdict: "infected",
|
||||
bucket: "uploads",
|
||||
key: "avatar.png",
|
||||
scannedAt: fixedNow,
|
||||
engine: "clamav-1.4",
|
||||
signature: "Eicar-Test-Signature",
|
||||
quarantineKey: "quarantine/uploads/avatar.png",
|
||||
quarantine: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves quarantineKey undefined when neither scanner nor adapter provide one", async () => {
|
||||
const service = createService({
|
||||
scanner: {
|
||||
scanObject: vi.fn().mockResolvedValue({
|
||||
verdict: "infected",
|
||||
signature: "Eicar-Test-Signature",
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const result = await service.scanObject({ bucket: "uploads", key: "avatar.png" });
|
||||
|
||||
expect(result).toMatchObject({
|
||||
verdict: "infected",
|
||||
signature: "Eicar-Test-Signature",
|
||||
quarantineKey: undefined,
|
||||
quarantine: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("createStorageScanService quarantine result without a quarantineKey", () => {
|
||||
it("falls back to the scanner quarantineKey when the adapter omits one", async () => {
|
||||
const service = createService({
|
||||
scanner: {
|
||||
scanObject: vi.fn().mockResolvedValue({
|
||||
verdict: "infected",
|
||||
signature: "Eicar-Test-Signature",
|
||||
quarantineKey: "quarantine/from-scanner.png",
|
||||
}),
|
||||
},
|
||||
quarantine: {
|
||||
// Adapter only tags the object in place; it returns no quarantineKey.
|
||||
quarantineObject: vi.fn().mockResolvedValue({ action: "tagged" }),
|
||||
},
|
||||
});
|
||||
|
||||
const result = await service.scanObject({ bucket: "uploads", key: "avatar.png" });
|
||||
|
||||
expect(result).toMatchObject({
|
||||
verdict: "infected",
|
||||
quarantineKey: "quarantine/from-scanner.png",
|
||||
quarantine: { action: "tagged" },
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers the adapter quarantineKey over the scanner one when both exist", async () => {
|
||||
const service = createService({
|
||||
scanner: {
|
||||
scanObject: vi.fn().mockResolvedValue({
|
||||
verdict: "infected",
|
||||
signature: "Eicar-Test-Signature",
|
||||
quarantineKey: "quarantine/from-scanner.png",
|
||||
}),
|
||||
},
|
||||
quarantine: {
|
||||
quarantineObject: vi.fn().mockResolvedValue({
|
||||
action: "moved",
|
||||
quarantineKey: "quarantine/from-adapter.png",
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const result = await service.scanObject({ bucket: "uploads", key: "avatar.png" });
|
||||
|
||||
expect(result).toMatchObject({
|
||||
verdict: "infected",
|
||||
quarantineKey: "quarantine/from-adapter.png",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("createStorageScanService upstream redaction edge cases", () => {
|
||||
it("yields all-undefined upstream fields for a record cause without diagnostics", async () => {
|
||||
const service = createService({
|
||||
scanner: {
|
||||
scanObject: vi.fn().mockRejectedValue({ leakedField: "do-not-copy" }),
|
||||
},
|
||||
});
|
||||
|
||||
const result = await service.scanObject({ bucket: "uploads", key: "avatar.png" });
|
||||
|
||||
expect(result.verdict).toBe("error");
|
||||
if (result.verdict !== "error") throw new Error("expected error verdict");
|
||||
expect(result.error.code).toBe("scanner_failed");
|
||||
expect(result.error.upstream?.name).toBeUndefined();
|
||||
expect(result.error.upstream?.message).toBeUndefined();
|
||||
expect(result.error.upstream?.status).toBeUndefined();
|
||||
expect(result.error.upstream?.requestId).toBeUndefined();
|
||||
expect(JSON.stringify(result)).not.toContain("do-not-copy");
|
||||
});
|
||||
|
||||
it("ignores a non-record $metadata and non-string name/message on the cause", async () => {
|
||||
const service = createService({
|
||||
scanner: {
|
||||
scanObject: vi.fn().mockRejectedValue({
|
||||
$metadata: 42,
|
||||
name: true,
|
||||
message: ["array-not-string"],
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const result = await service.scanObject({ bucket: "uploads", key: "avatar.png" });
|
||||
|
||||
expect(result.verdict).toBe("error");
|
||||
if (result.verdict !== "error") throw new Error("expected error verdict");
|
||||
expect(result.error.upstream?.status).toBeUndefined();
|
||||
expect(result.error.upstream?.requestId).toBeUndefined();
|
||||
expect(result.error.upstream?.name).toBeUndefined();
|
||||
expect(result.error.upstream?.message).toBeUndefined();
|
||||
expect(JSON.stringify(result)).not.toContain("array-not-string");
|
||||
});
|
||||
});
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
// @vitest-environment node
|
||||
import { Buffer } from "node:buffer";
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
// Force file-type's signature reader to throw so detectMimeType()'s catch
|
||||
// returns undefined. The adapter must then fall through to the undetectable
|
||||
// path rather than propagating the error to the caller.
|
||||
vi.mock("file-type", () => ({
|
||||
fileTypeFromBuffer: vi.fn(async () => {
|
||||
throw new Error("corrupt signature table");
|
||||
}),
|
||||
}));
|
||||
|
||||
import { createMagicBytesScanAdapter } from "./magic-bytes-adapter.js";
|
||||
|
||||
const REAL_PNG = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
const asUint8 = (buf: Buffer): Uint8Array => new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||
|
||||
describe("magic-bytes-adapter when file-type throws", () => {
|
||||
test("treats a thrown detector error as an undetectable MIME (does not propagate)", async () => {
|
||||
const adapter = createMagicBytesScanAdapter();
|
||||
const result = await adapter.scan({
|
||||
buffer: asUint8(REAL_PNG),
|
||||
declaredMimeType: "image/png",
|
||||
filename: "avatar.png",
|
||||
context: "avatar",
|
||||
});
|
||||
|
||||
expect(result.status).toBe("rejected");
|
||||
expect(result.reason).toBe("mime_undetectable");
|
||||
expect(result.detail).toContain("image/png");
|
||||
});
|
||||
|
||||
test("still honors the text/plain fallback when the detector throws", async () => {
|
||||
const adapter = createMagicBytesScanAdapter({
|
||||
allowList: {
|
||||
avatar: [],
|
||||
mediaLibrary: [],
|
||||
emailAttachment: ["text/plain"],
|
||||
formUpload: [],
|
||||
kbAsset: [],
|
||||
},
|
||||
});
|
||||
const buffer = new TextEncoder().encode("plain text body");
|
||||
const result = await adapter.scan({
|
||||
buffer,
|
||||
declaredMimeType: "text/plain",
|
||||
filename: "notes.txt",
|
||||
context: "emailAttachment",
|
||||
});
|
||||
|
||||
expect(result.status).toBe("clean");
|
||||
});
|
||||
});
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
// @vitest-environment node
|
||||
import { Buffer } from "node:buffer";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { createMagicBytesScanAdapter } from "./magic-bytes-adapter.js";
|
||||
import type { PreUploadAllowList } from "./pre-upload-types.js";
|
||||
|
||||
const REAL_PNG = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
const asUint8 = (buf: Buffer): Uint8Array => new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||
|
||||
describe("magic-bytes-adapter filename guard edge cases", () => {
|
||||
test("rejects an empty filename before inspecting the buffer", async () => {
|
||||
const adapter = createMagicBytesScanAdapter();
|
||||
const result = await adapter.scan({
|
||||
buffer: asUint8(REAL_PNG),
|
||||
declaredMimeType: "image/png",
|
||||
filename: "",
|
||||
context: "avatar",
|
||||
});
|
||||
expect(result.status).toBe("rejected");
|
||||
expect(result.reason).toBe("filename_invalid");
|
||||
expect(result.detail).toBe("filename was empty");
|
||||
});
|
||||
|
||||
test("rejects a non-string filename without throwing", async () => {
|
||||
const adapter = createMagicBytesScanAdapter();
|
||||
const result = await adapter.scan({
|
||||
buffer: asUint8(REAL_PNG),
|
||||
declaredMimeType: "image/png",
|
||||
// Defensive: a caller passing a non-string from untyped JSON must be
|
||||
// rejected, not crash the scanner.
|
||||
filename: undefined as unknown as string,
|
||||
context: "avatar",
|
||||
});
|
||||
expect(result.status).toBe("rejected");
|
||||
expect(result.reason).toBe("filename_invalid");
|
||||
});
|
||||
|
||||
test("falls back to an empty allow-list when the context key is missing", async () => {
|
||||
// Defensive: a partial allow-list (e.g. built from incomplete env config)
|
||||
// that omits the requested context must reject rather than throw — the
|
||||
// `allowList[context] ?? []` guard yields an empty, deny-all list.
|
||||
const partialAllowList = { mediaLibrary: ["image/png"] } as unknown as PreUploadAllowList;
|
||||
const adapter = createMagicBytesScanAdapter({ allowList: partialAllowList });
|
||||
const result = await adapter.scan({
|
||||
buffer: asUint8(REAL_PNG),
|
||||
declaredMimeType: "image/png",
|
||||
filename: "avatar.png",
|
||||
context: "avatar",
|
||||
});
|
||||
expect(result.status).toBe("rejected");
|
||||
expect(result.reason).toBe("mime_not_allowed");
|
||||
});
|
||||
|
||||
test("trims and lowercases the declared MIME before matching", async () => {
|
||||
const adapter = createMagicBytesScanAdapter();
|
||||
const result = await adapter.scan({
|
||||
buffer: asUint8(REAL_PNG),
|
||||
declaredMimeType: " IMAGE/PNG ",
|
||||
filename: "avatar.png",
|
||||
context: "avatar",
|
||||
});
|
||||
expect(result.status).toBe("clean");
|
||||
expect(result.detectedMimeType).toBe("image/png");
|
||||
});
|
||||
});
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { StorageScanError, type StorageScanDiagnostic } from "./index.js";
|
||||
|
||||
describe("StorageScanError", () => {
|
||||
const details: StorageScanDiagnostic = { code: "scanner_failed", message: "scan boom" };
|
||||
|
||||
it("carries the code, details, and underlying cause", () => {
|
||||
const cause = new Error("clamd down");
|
||||
const error = new StorageScanError("scanner_failed", "Storage scanner failed.", details, { cause });
|
||||
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
expect(error.name).toBe("StorageScanError");
|
||||
expect(error.message).toBe("Storage scanner failed.");
|
||||
expect(error.code).toBe("scanner_failed");
|
||||
expect(error.details).toEqual(details);
|
||||
expect(error.cause).toBe(cause);
|
||||
});
|
||||
|
||||
it("defaults cause to undefined when no options are passed", () => {
|
||||
const error = new StorageScanError("invalid_target", "Bad target.", {
|
||||
code: "invalid_target",
|
||||
message: "Bad target.",
|
||||
});
|
||||
expect(error.cause).toBeUndefined();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user