Files
co-lite/solvway-admin-portal/app/api/admin/member-messages/routes.hardening.test.ts
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 15:55:45 +08:00

110 lines
5.3 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { NextRequest } from "next/server";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET as list } from "./route";
import { GET as byKey } from "./by-key/route";
import { GET as messages } from "./[uuid]/messages/route";
import { POST as upload } from "./images/route";
import { GET as image } from "./[uuid]/messages/[messageUuid]/images/[index]/route";
const B = "http://localhost/api/admin/member-messages";
const get = (url: string) => new Request(url) as unknown as NextRequest;
const img = (messageUuid = "m1") => ({ params: Promise.resolve({ uuid: "c1", messageUuid, index: "0" }) });
const formReq = (fd: FormData, headers: Record<string, string> = {}) =>
({ headers: new Headers(headers), formData: async () => fd }) as unknown as NextRequest;
const pngForm = () => {
const fd = new FormData();
fd.append("file", new File(["abc"], "a.png", { type: "image/png" }));
return fd;
};
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} });
mocks.getToken.mockReset().mockResolvedValue("jwt");
process.env.MOBILE_API_BASE_URL = "http://up";
process.env.MOBILE_API_KEY = "k";
});
afterEach(() => vi.unstubAllGlobals());
describe("query whitelist", () => {
it("forwards only the documented query keys", async () => {
await list(get(`${B}?types=S&q=x&page=1&size=20&unreadOnly=true&reader=M:MY3&adminUsername=eve`));
await byKey(get(`${B}/by-key?member=MY5&reader=M:MY3`));
await messages(get(`${B}/c1/messages?before=m9&size=30&reader=M:MY3`), { params: Promise.resolve({ uuid: "c1" }) });
const urls = mocks.callMobileApi.mock.calls.map((c) => c[0] as string);
expect(urls[0]).toBe("/api/admin/member-messages?types=S&unreadOnly=true&q=x&page=1&size=20");
expect(urls[1]).toBe("/api/admin/member-messages/by-key?member=MY5");
expect(urls[2]).toBe("/api/admin/member-messages/c1/messages?before=m9&size=30");
});
it("passes a module-denied 403 through for the blocked state", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 403, error: "The BO_MEMBER_MESSAGES module is required." });
const res = await list(get(B));
expect(res.status).toBe(403);
});
});
describe("upload", () => {
it("refuses a declared body far over 5 MB before reading it", async () => {
const formData = vi.fn();
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const res = await upload({ headers: new Headers({ "content-length": String(7 * 1024 * 1024) }), formData } as unknown as NextRequest);
expect(res.status).toBe(400);
expect(formData).not.toHaveBeenCalled();
expect(fetchMock).not.toHaveBeenCalled();
});
it("forwards the file under the `file` field", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ ref: "messages/admin/1.png" }), { status: 200 }));
vi.stubGlobal("fetch", fetchMock);
const res = await upload(formReq(pngForm()));
expect(await res.json()).toEqual({ ref: "messages/admin/1.png" });
expect((fetchMock.mock.calls[0][1].body as FormData).get("file")).toBeInstanceOf(File);
});
it("answers 502 when a 200 reply has no ref", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("<html/>", { status: 200 })));
expect((await upload(formReq(pngForm()))).status).toBe(502);
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("{}", { status: 200 })));
expect((await upload(formReq(pngForm()))).status).toBe(502);
});
it("maps mobile-api's expired-token 500 to 401", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("JWT expired token", { status: 500 })));
expect((await upload(formReq(pngForm()))).status).toBe(401);
});
});
describe("image stream", () => {
it("never serves a non-image type as-is and sets nosniff", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("<script>", { status: 200, headers: { "content-type": "text/html" } })));
const res = await image(get(`${B}/c1/messages/m1/images/0`), img());
expect(res.headers.get("content-type")).toBe("application/octet-stream");
expect(res.headers.get("x-content-type-options")).toBe("nosniff");
});
it("keeps an image type and pipes the body", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("png", { status: 200, headers: { "content-type": "image/png" } })));
const res = await image(get(`${B}/c1/messages/m1/images/0`), img());
expect(res.headers.get("content-type")).toBe("image/png");
expect(await res.text()).toBe("png");
});
it("refuses a malformed message id without calling upstream", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
expect((await image(get(B), img("../x"))).status).toBe(400);
expect(fetchMock).not.toHaveBeenCalled();
});
it("maps mobile-api's expired-token 500 to 401", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("invalid token", { status: 500 })));
expect((await image(get(B), img())).status).toBe(401);
});
});