fix: release QA hardening across processing, media, security, and CI gates (#649)

A release-readiness QA pass over the whole product. The commits split into
defects a user would hit and gates that were reporting green while measuring
nothing.

## Fixes that change behaviour

Rate limiting was bypassable on every install: TRUST_PROXY defaulted to true, so
request.ip came from a client-set header and a forged X-Forwarded-For got past
the login limiter. The default is now a private-network trust list.

A transient Postgres outage stranded in-flight jobs, leaving finished output on
disk with no row pointing at it. A reconciler now resolves those rows and adopts
the bytes rather than dropping the work.

A Redis connection that moved to a new address wedged every read-blocked
consumer, so completions stopped signalling while health still answered 200.
Socket timeouts plus subscriber pings recover it.

Installing more than one AI bundle left the shared venv multi-versioned and
silently broke three tools. The installer now reconciles distributions to one
version each.

Converting an image to JXL at quality 1 through 4 returned a 500, because
libjxl 0.7 rejects the distance those values compute. The quality is floored at
what the encoder honours. A missing ffmpeg was also reported to the user as a
corrupt upload; it now says the engine is unavailable.

RAW uploads reached an unpatched LibRaw on arm64, so it is built from source at
0.22.2, and the release scan was split so it can fail on an unfixed critical
instead of hiding it behind ignore-unfixed.

## Gates that could not fail

Two mutation lanes ran zero mutants because Stryker crawled the gitignored docs
build; coverage discarded its whole report on any failing test; the lint gate
skipped root tests, scripts, and two workspaces; and several generated matrices
counted a host missing ffmpeg as a passing tool. Each now measures what it
claims.

Full evidence and the outstanding release items are tracked locally and are not
part of this branch.
This commit is contained in:
SnapOtter
2026-07-27 15:37:30 +08:00
committed by GitHub
parent bc32f86a07
commit d10d0f544f
855 changed files with 54564 additions and 13092 deletions
@@ -1,17 +1,24 @@
/**
* Integration tests for the background-replace tool (/api/v1/tools/image/background-replace).
*
* This tool reuses the rembg bundle (background-removal). The 501 gate fires
* before any settings validation when the bundle is absent. Locally and in CI,
* the bundle is never installed, so the 501 surface is always exercised.
* This tool reuses the rembg bundle (background-removal). Missing-bundle
* contracts run only when that capability is absent; installed happy paths run
* when it is detected or REQUIRE_AI_FEATURES makes absence a release failure.
*
* The compositeOnColor helper has dedicated unit coverage in
* tests/unit/api/background-composite.test.ts. The rembg model never runs
* locally; bundle-gated happy paths are in a skipped describe.
* tests/unit/api/background-composite.test.ts.
*/
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { isToolInstalled } from "../../../../apps/api/src/lib/feature-status.js";
import { fixtures, readFixture } from "../../../fixtures/index.js";
import { installedAiCapabilityGate } from "../../../helpers/installed-ai-capability-gate.js";
import {
expectConfiguredBackground,
expectForegroundPreserved,
expectObservablePixelChange,
} from "../../../helpers/installed-ai-output-oracles.js";
import { waitForDownloadedJobArtifact } from "../../settle-job.js";
import {
buildTestApp,
createMultipartPayload,
@@ -20,6 +27,13 @@ import {
} from "../../test-server.js";
const PNG = readFixture(fixtures.image.base.png200);
const PORTRAIT = readFixture(fixtures.image.portrait.jpg);
const REQUIRE_AI_FEATURES = process.env.REQUIRE_AI_FEATURES === "1";
const AI_CAPABILITY = installedAiCapabilityGate(
"background-replace",
REQUIRE_AI_FEATURES,
isToolInstalled,
);
let testApp: TestApp;
let app: TestApp["app"];
@@ -36,31 +50,34 @@ afterAll(async () => {
}, 10_000);
describe("background-replace", () => {
// -- 501 gate (always fires locally: background-removal bundle never installed) --
// -- Missing-capability contract --
it("returns 501 FEATURE_NOT_INSTALLED when bundle is absent", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({}) },
]);
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"returns 501 FEATURE_NOT_INSTALLED when bundle is absent",
async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/background-replace",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/background-replace",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
expect(json.feature).toBe("background-removal");
expect(json.featureName).toBe("Background Removal");
expect(json.estimatedSize).toBeDefined();
});
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
expect(json.feature).toBe("background-removal");
expect(json.featureName).toBe("Background Removal");
expect(json.estimatedSize).toBeDefined();
},
);
// -- Auth gate --
@@ -82,96 +99,12 @@ describe("background-replace", () => {
// -- Validation: 501 fires before settings parse, so bad hex also 501s --
it("returns 501 even with invalid color hex (gate fires first)", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ color: "not-a-hex" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/background-replace",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
// 501 because the bundle gate fires before settings validation
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
});
it("returns 501 with gradient settings (gate fires first)", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{
name: "settings",
content: JSON.stringify({
backgroundType: "gradient",
gradientColor1: "#ff0000",
gradientColor2: "#0000ff",
gradientAngle: 90,
}),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/background-replace",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
});
it("returns 501 with feather and webp format (gate fires first)", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{
name: "settings",
content: JSON.stringify({
backgroundType: "color",
color: "#00ff00",
feather: 5,
format: "webp",
}),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/background-replace",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
});
// -- Bundle-gated happy path (skipped: background-removal bundle is 4-5 GB) --
// The background-removal bundle is not installed in any verification environment.
// These tests exist for future in-container runs after bundle install.
// The 501 contract + compositeOnColor unit tests carry the verification.
describe.skip("with background-removal bundle installed", () => {
it("replaces background with color (202 + async)", async () => {
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"returns 501 even with invalid color hex (gate fires first)",
async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ color: "#ff0000" }) },
{ name: "settings", content: JSON.stringify({ color: "not-a-hex" }) },
]);
const res = await app.inject({
@@ -184,13 +117,16 @@ describe("background-replace", () => {
body,
});
expect(res.statusCode).toBe(202);
// 501 because the bundle gate fires before settings validation
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.jobId).toBeDefined();
expect(json.async).toBe(true);
}, 300_000);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
},
);
it("replaces background with gradient (202 + async)", async () => {
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"returns 501 with gradient settings (gate fires first)",
async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{
@@ -199,8 +135,38 @@ describe("background-replace", () => {
backgroundType: "gradient",
gradientColor1: "#ff0000",
gradientColor2: "#0000ff",
gradientAngle: 45,
feather: 3,
gradientAngle: 90,
}),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/background-replace",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
},
);
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"returns 501 with feather and webp format (gate fires first)",
async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{
name: "settings",
content: JSON.stringify({
backgroundType: "color",
color: "#00ff00",
feather: 5,
format: "webp",
}),
},
@@ -216,10 +182,104 @@ describe("background-replace", () => {
body,
});
expect(res.statusCode).toBe(202);
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.jobId).toBeDefined();
expect(json.async).toBe(true);
}, 300_000);
});
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
},
);
// -- Installed/required capability contract --
describe.skipIf(!AI_CAPABILITY.runInstalledContract)(
"with background-removal bundle installed",
() => {
it("replaces background with color (202 + async)", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "portrait-color.jpg",
contentType: "image/jpeg",
content: PORTRAIT,
},
{ name: "settings", content: JSON.stringify({ color: "#ff0000" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/background-replace",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(202);
const json = JSON.parse(res.body);
expect(json.jobId).toBeDefined();
expect(json.async).toBe(true);
const artifact = await waitForDownloadedJobArtifact(
app,
adminToken,
"background-replace",
json.jobId as string,
240_000,
);
expect(artifact.filename).toBe("portrait-color_bg.png");
expect(artifact.contentType).toBe("image/png");
await expectObservablePixelChange(PORTRAIT, artifact.buffer);
await expectConfiguredBackground(artifact.buffer, "solid-red");
await expectForegroundPreserved(PORTRAIT, artifact.buffer);
}, 300_000);
it("replaces background with gradient (202 + async)", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "portrait-color.jpg",
contentType: "image/jpeg",
content: PORTRAIT,
},
{
name: "settings",
content: JSON.stringify({
backgroundType: "gradient",
gradientColor1: "#ff0000",
gradientColor2: "#0000ff",
gradientAngle: 45,
feather: 3,
format: "webp",
}),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/background-replace",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(202);
const json = JSON.parse(res.body);
expect(json.jobId).toBeDefined();
expect(json.async).toBe(true);
const artifact = await waitForDownloadedJobArtifact(
app,
adminToken,
"background-replace",
json.jobId as string,
240_000,
);
expect(artifact.filename).toBe("portrait-color_bg.webp");
expect(artifact.contentType).toBe("image/webp");
await expectObservablePixelChange(PORTRAIT, artifact.buffer);
await expectConfiguredBackground(artifact.buffer, "red-blue-gradient");
await expectForegroundPreserved(PORTRAIT, artifact.buffer);
}, 300_000);
},
);
});
@@ -9,6 +9,7 @@
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { getToolConfig } from "../../../../apps/api/src/routes/tool-factory.js";
import { fixtures, readFixture } from "../../../fixtures/index.js";
import {
buildTestApp,
@@ -769,6 +770,22 @@ describe("Beautify", () => {
expect(meta.hasAlpha).toBe(true);
});
it("pipeline image background without a second input falls back to transparent", async () => {
const config = getToolConfig("beautify");
if (!config) throw new Error("beautify must be registered");
const settings = config.settingsSchema.parse({
backgroundType: "image",
shadowPreset: "none",
padding: 20,
});
const result = await config.process(PNG, settings, "test.png");
const meta = await sharp(result.buffer).metadata();
expect(result.filename).toBe("test.png");
expect(meta.hasAlpha).toBe(true);
});
it("shadow with zero padding (shadow extends beyond image)", async () => {
const payload = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
@@ -931,6 +948,19 @@ describe("Beautify", () => {
expect(res.statusCode).toBe(400);
});
it("empty custom shadow color returns 400 instead of reaching Sharp", async () => {
const payload = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{
name: "settings",
content: JSON.stringify({ shadowPreset: "custom", shadowColor: "" }),
},
]);
const res = await post("/api/v1/tools/image/beautify", payload);
expect(res.statusCode).toBe(400);
});
it("invalid background type returns 400", async () => {
const payload = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
@@ -1,17 +1,23 @@
/**
* Integration tests for the blur-background tool (/api/v1/tools/image/blur-background).
*
* This tool reuses the rembg bundle (background-removal). The 501 gate fires
* before any settings validation when the bundle is absent. Locally and in CI,
* the bundle is never installed, so the 501 surface is always exercised.
* This tool reuses the rembg bundle (background-removal). Missing-bundle
* contracts run only when that capability is absent; installed happy paths run
* when it is detected or REQUIRE_AI_FEATURES makes absence a release failure.
*
* The blurBackground helper has dedicated unit coverage in
* tests/unit/api/background-composite.test.ts. The rembg model never runs
* locally; bundle-gated happy paths are in a skipped describe.
* tests/unit/api/background-composite.test.ts.
*/
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { isToolInstalled } from "../../../../apps/api/src/lib/feature-status.js";
import { fixtures, readFixture } from "../../../fixtures/index.js";
import { installedAiCapabilityGate } from "../../../helpers/installed-ai-capability-gate.js";
import {
expectForegroundPreserved,
expectObservablePixelChange,
} from "../../../helpers/installed-ai-output-oracles.js";
import { waitForDownloadedJobArtifact } from "../../settle-job.js";
import {
buildTestApp,
createMultipartPayload,
@@ -20,6 +26,13 @@ import {
} from "../../test-server.js";
const PNG = readFixture(fixtures.image.base.png200);
const PORTRAIT = readFixture(fixtures.image.portrait.jpg);
const REQUIRE_AI_FEATURES = process.env.REQUIRE_AI_FEATURES === "1";
const AI_CAPABILITY = installedAiCapabilityGate(
"blur-background",
REQUIRE_AI_FEATURES,
isToolInstalled,
);
let testApp: TestApp;
let app: TestApp["app"];
@@ -36,31 +49,34 @@ afterAll(async () => {
}, 10_000);
describe("blur-background", () => {
// -- 501 gate (always fires locally: background-removal bundle never installed) --
// -- Missing-capability contract --
it("returns 501 FEATURE_NOT_INSTALLED when bundle is absent", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ intensity: 50, feather: 5, format: "png" }) },
]);
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"returns 501 FEATURE_NOT_INSTALLED when bundle is absent",
async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ intensity: 50, feather: 5, format: "png" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/blur-background",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/blur-background",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
expect(json.feature).toBe("background-removal");
expect(json.featureName).toBe("Background Removal");
expect(json.estimatedSize).toBeDefined();
});
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
expect(json.feature).toBe("background-removal");
expect(json.featureName).toBe("Background Removal");
expect(json.estimatedSize).toBeDefined();
},
);
// -- Auth gate --
@@ -82,86 +98,41 @@ describe("blur-background", () => {
// -- Validation: 501 fires before settings parse, so intensity=0 also 501s --
it("returns 501 even with invalid intensity (gate fires first)", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ intensity: 0, feather: 25, format: "bmp" }) },
]);
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"returns 501 even with invalid intensity (gate fires first)",
async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ intensity: 0, feather: 25, format: "bmp" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/blur-background",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/blur-background",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
// 501 because the bundle gate fires before settings validation
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
});
// 501 because the bundle gate fires before settings validation
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
},
);
// -- 501 with webp format (still gated) --
it("returns 501 with webp format and feather settings", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ intensity: 80, feather: 10, format: "webp" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/blur-background",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
});
// -- 501 with defaults (empty settings object, Zod fills defaults) --
it("returns 501 with empty settings (defaults applied by Zod)", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/blur-background",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
});
// -- Bundle-gated happy path (skipped: background-removal bundle is 4-5 GB) --
// The background-removal bundle is not installed in any verification environment.
// These tests exist for future in-container runs after bundle install.
// The 501 contract + blurBackground unit tests carry the verification.
describe.skip("with background-removal bundle installed", () => {
it("blurs background with full settings (202 + async)", async () => {
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"returns 501 with webp format and feather settings",
async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{
name: "settings",
content: JSON.stringify({ intensity: 75, feather: 3, format: "webp" }),
content: JSON.stringify({ intensity: 80, feather: 10, format: "webp" }),
},
]);
@@ -175,10 +146,83 @@ describe("blur-background", () => {
body,
});
expect(res.statusCode).toBe(202);
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.jobId).toBeDefined();
expect(json.async).toBe(true);
}, 300_000);
});
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
},
);
// -- 501 with defaults (empty settings object, Zod fills defaults) --
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"returns 501 with empty settings (defaults applied by Zod)",
async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/blur-background",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
},
);
// -- Installed/required capability contract --
describe.skipIf(!AI_CAPABILITY.runInstalledContract)(
"with background-removal bundle installed",
() => {
it("blurs background with full settings (202 + async)", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "portrait-color.jpg",
contentType: "image/jpeg",
content: PORTRAIT,
},
{
name: "settings",
content: JSON.stringify({ intensity: 75, feather: 3, format: "webp" }),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/blur-background",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(202);
const json = JSON.parse(res.body);
expect(json.jobId).toBeDefined();
expect(json.async).toBe(true);
const artifact = await waitForDownloadedJobArtifact(
app,
adminToken,
"blur-background",
json.jobId as string,
240_000,
);
expect(artifact.filename).toBe("portrait-color_blurbg.webp");
expect(artifact.contentType).toBe("image/webp");
await expectObservablePixelChange(PORTRAIT, artifact.buffer);
await expectForegroundPreserved(PORTRAIT, artifact.buffer);
}, 300_000);
},
);
});
@@ -6,8 +6,6 @@
* Consolidated adjust-colors tool replaces the old brightness-contrast, saturation, etc.
*/
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { apiToolPath } from "@snapotter/shared";
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
@@ -7,7 +7,7 @@
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { fixtureDir, fixtures, readFixture } from "../../../fixtures/index.js";
import { fixtures, readFixture } from "../../../fixtures/index.js";
import {
buildTestApp,
createMultipartPayload,
@@ -15,7 +15,6 @@ import {
type TestApp,
} from "../../test-server.js";
const FORMATS = fixtureDir.formats;
const PNG = readFixture(fixtures.image.base.png200);
const _JPG = readFixture(fixtures.image.base.jpg100);
const WEBP = readFixture(fixtures.image.base.webp50);
@@ -173,6 +173,11 @@ describe("Field removal", () => {
if (res.statusCode === 422) return;
expect(res.statusCode).toBe(200);
});
it("rejects empty and unsafe field names at the API boundary", async () => {
expect((await postTool({ fieldsToRemove: [""] })).statusCode).toBe(400);
expect((await postTool({ fieldsToRemove: ["bad field"] })).statusCode).toBe(400);
});
});
// ── Keywords ────────────────────────────────────────────────────
@@ -5,8 +5,10 @@
* plus the metadata endpoint. Uses a real Fastify server with in-memory SQLite.
*/
import { isToolInputError } from "@snapotter/shared";
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { getToolConfig } from "../../../../apps/api/src/routes/tool-factory.js";
import { fixtures, readFixture } from "../../../fixtures/index.js";
import {
buildTestApp,
@@ -105,6 +107,47 @@ describe("POST /api/v1/tools/image/gif-tools/info", () => {
// ── Resize mode ───────────────────────────────────────────────────
describe("Resize mode", () => {
it("rejects an animated resize whose aggregate output exceeds the pixel budget", async () => {
const { body: payload, contentType } = makePayload({
mode: "resize",
width: 5_000,
height: 5_000,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/gif-tools",
payload,
headers: {
"content-type": contentType,
authorization: `Bearer ${adminToken}`,
},
});
expect(res.statusCode).toBe(400);
expect(res.json().error).toMatch(/total pixel/i);
});
it("rejects the same oversized workload through the worker contract", async () => {
const config = getToolConfig("gif-tools");
expect(config).toBeDefined();
const settings = config?.settingsSchema.parse({
mode: "resize",
width: 5_000,
height: 5_000,
});
let caught: unknown;
try {
await config?.process(animatedGif, settings, "test.gif");
} catch (error) {
caught = error;
}
expect(isToolInputError(caught)).toBe(true);
expect(caught).toHaveProperty("message", expect.stringMatching(/total pixel/i));
});
it("resizes animated GIF by pixel dimensions", async () => {
const { body: payload, contentType } = makePayload({
mode: "resize",
@@ -5,7 +5,6 @@
* and extension validation.
*/
import { join } from "node:path";
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { fixtures, readFixture } from "../../../fixtures/index.js";
@@ -1,5 +1,4 @@
import sharp from "sharp";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { buildTestApp, loginAsAdmin, type TestApp } from "../../test-server.js";
// Mock the browser service -- Chromium may not be available in CI
@@ -181,39 +181,40 @@ describe("ocr tier execution coverage", () => {
expect(maxActive).toBe(1);
});
it.each(
OCR_FORMAT_FIXTURES,
)("prepares %s through the real image ingress before mocked recognition", async (fixture) => {
mocks.getOcrRuntimeCapability.mockReturnValue({
available: false,
qualities: [],
providers: [],
});
mocks.extractText.mockImplementationOnce(async (_input, _scratch, options) => ({
text: "format accepted",
engine: "tesseract",
requestedQuality: options.quality,
actualQuality: options.quality,
device: "cpu",
provider: "tesseract",
degraded: false,
warnings: [],
}));
it.each(OCR_FORMAT_FIXTURES)(
"prepares %s through the real image ingress before mocked recognition",
async (fixture) => {
mocks.getOcrRuntimeCapability.mockReturnValue({
available: false,
qualities: [],
providers: [],
});
mocks.extractText.mockImplementationOnce(async (_input, _scratch, options) => ({
text: "format accepted",
engine: "tesseract",
requestedQuality: options.quality,
actualQuality: options.quality,
device: "cpu",
provider: "tesseract",
degraded: false,
warnings: [],
}));
const response = await postOcrFile(
{ quality: "fast", language: "en" },
readFileSync(join(fixtureDir.formats, fixture)),
fixture,
);
const result = await awaitAcceptedOcr(response);
const response = await postOcrFile(
{ quality: "fast", language: "en" },
readFileSync(join(fixtureDir.formats, fixture)),
fixture,
);
const result = await awaitAcceptedOcr(response);
expect(result).toMatchObject({
text: "format accepted",
requestedQuality: "fast",
actualQuality: "fast",
});
expect(mocks.extractText).toHaveBeenCalledTimes(1);
});
expect(result).toMatchObject({
text: "format accepted",
requestedQuality: "fast",
actualQuality: "fast",
});
expect(mocks.extractText).toHaveBeenCalledTimes(1);
},
);
it("fails closed when the selected best runtime crashes", async () => {
mocks.extractText.mockRejectedValueOnce(new Error("OCR runtime exited unexpectedly"));
@@ -141,6 +141,12 @@ describe("Resize", () => {
expect(meta.height).toBe(75);
});
it("treats 1000 percent as 10x at the product boundary", async () => {
const meta = await resizeAndMeta({ percentage: 1000 }, TINY, "tiny.png", "image/png");
expect(meta.width).toBe(10);
expect(meta.height).toBe(10);
});
it("respects withoutEnlargement flag", async () => {
const meta = await resizeAndMeta({ width: 400, height: 300, withoutEnlargement: true });
// Should not enlarge beyond original 200x150
@@ -259,6 +265,52 @@ describe("Resize", () => {
expect(result.error).toMatch(/invalid settings/i);
});
it("rejects the deterministic oversized percentage before processing", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{
name: "settings",
content: JSON.stringify({ percentage: 896202.8004871072 }),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/resize",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(400);
expect(JSON.parse(res.body).details).toMatch(/less than or equal to 1000/i);
});
it("rejects a percentage immediately above the product boundary", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "tiny.png", contentType: "image/png", content: TINY },
{
name: "settings",
content: JSON.stringify({ percentage: 1000.000001 }),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/resize",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(400);
expect(JSON.parse(res.body).details).toMatch(/less than or equal to 1000/i);
});
it("rejects unauthenticated requests", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
@@ -112,6 +112,12 @@ describe("Rotate", () => {
expect(meta.height).toBe(200);
});
it("normalizes large finite angles before passing them to Sharp", async () => {
const meta = await rotateAndMeta({ angle: 10_000_000.000000002 });
expect(meta.width).toBeGreaterThan(0);
expect(meta.height).toBeGreaterThan(0);
});
it("rotates 0 degrees (no-op)", async () => {
const meta = await rotateAndMeta({ angle: 0 });
expect(meta.width).toBe(200);
@@ -149,8 +149,7 @@ describe("Sprite Sheet", () => {
body,
});
// The factory wraps InputValidationError as 422
expect(res.statusCode).toBeGreaterThanOrEqual(400);
expect(res.statusCode).toBeLessThan(500);
expect(res.statusCode).toBe(400);
expect(JSON.parse(res.body).error).toMatch(/at least 2 files/i);
});
});
@@ -80,28 +80,25 @@ describe("watermark-image", () => {
expect(Buffer.from(dlRes.rawPayload).equals(PNG)).toBe(false);
});
it.each([
"center",
"top-left",
"top-right",
"bottom-left",
"bottom-right",
] as const)("supports position: %s", async (position) => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "main.png", contentType: "image/png", content: PNG },
{ name: "watermark", filename: "wm.png", contentType: "image/png", content: SMALL_PNG },
{ name: "settings", content: JSON.stringify({ position }) },
]);
it.each(["center", "top-left", "top-right", "bottom-left", "bottom-right"] as const)(
"supports position: %s",
async (position) => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "main.png", contentType: "image/png", content: PNG },
{ name: "watermark", filename: "wm.png", contentType: "image/png", content: SMALL_PNG },
{ name: "settings", content: JSON.stringify({ position }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/watermark-image",
headers: { authorization: `Bearer ${adminToken}`, "content-type": contentType },
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/watermark-image",
headers: { authorization: `Bearer ${adminToken}`, "content-type": contentType },
body,
});
expect(res.statusCode).toBe(200);
});
expect(res.statusCode).toBe(200);
},
);
it("respects custom opacity and scale", async () => {
const { body, contentType } = createMultipartPayload([
@@ -77,30 +77,26 @@ describe("watermark-text", () => {
expect(Buffer.from(dlRes.rawPayload).equals(PNG)).toBe(false);
});
it.each([
"center",
"top-left",
"top-right",
"bottom-left",
"bottom-right",
"tiled",
] as const)("supports position: %s", async (position) => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ text: "Pos", position }) },
]);
it.each(["center", "top-left", "top-right", "bottom-left", "bottom-right", "tiled"] as const)(
"supports position: %s",
async (position) => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ text: "Pos", position }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/watermark-text",
headers: { authorization: `Bearer ${adminToken}`, "content-type": contentType },
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/watermark-text",
headers: { authorization: `Bearer ${adminToken}`, "content-type": contentType },
body,
});
expect(res.statusCode).toBe(200);
const json = JSON.parse(res.body);
expect(json.downloadUrl).toBeDefined();
});
expect(res.statusCode).toBe(200);
const json = JSON.parse(res.body);
expect(json.downloadUrl).toBeDefined();
},
);
it("respects custom opacity and font size", async () => {
const { body, contentType } = createMultipartPayload([