163 lines
5.9 KiB
TypeScript
163 lines
5.9 KiB
TypeScript
import { spawn } from "node:child_process";
|
||
import { once } from "node:events";
|
||
import { fileURLToPath } from "node:url";
|
||
import { afterEach, describe, expect, it } from "vitest";
|
||
import type { FastifyInstance } from "fastify";
|
||
import { buildApp } from "../src/app.ts";
|
||
import { parsePort } from "../src/config.ts";
|
||
|
||
const ENTRY = fileURLToPath(new URL("../src/index.ts", import.meta.url));
|
||
|
||
function runServer(env: Record<string, string>) {
|
||
const child = spawn(process.execPath, [ENTRY], {
|
||
env: { PATH: process.env.PATH ?? "", ...env },
|
||
stdio: ["ignore", "pipe", "pipe"],
|
||
});
|
||
let stderr = "";
|
||
let stdout = "";
|
||
child.stderr.on("data", (d: Buffer) => (stderr += d.toString()));
|
||
child.stdout.on("data", (d: Buffer) => (stdout += d.toString()));
|
||
return { child, out: () => stdout, err: () => stderr };
|
||
}
|
||
|
||
async function waitFor(fn: () => boolean, timeoutMs = 10_000): Promise<void> {
|
||
const start = Date.now();
|
||
while (!fn()) {
|
||
if (Date.now() - start > timeoutMs) throw new Error("timeout");
|
||
await new Promise((r) => setTimeout(r, 50));
|
||
}
|
||
}
|
||
|
||
describe("Requirement: Порт из окружения", () => {
|
||
it("Scenario: Запуск на заданном порту", async () => {
|
||
const port = String(41000 + Math.floor(Math.random() * 1000));
|
||
const srv = runServer({ PORT: port, LOG_LEVEL: "info" });
|
||
try {
|
||
await waitFor(() => srv.out().includes("Server listening"));
|
||
const res = await fetch(`http://127.0.0.1:${port}/healthz`);
|
||
expect(res.status).toBe(200);
|
||
} finally {
|
||
srv.child.kill("SIGTERM");
|
||
await once(srv.child, "exit");
|
||
}
|
||
});
|
||
|
||
it("Scenario: Некорректный порт", async () => {
|
||
const srv = runServer({ PORT: "abc" });
|
||
const [code] = (await once(srv.child, "exit")) as [number | null];
|
||
expect(code).not.toBe(0);
|
||
expect(srv.err()).toContain("Invalid PORT");
|
||
});
|
||
|
||
it.each(["0", "65536", "-1", "3000.5", " 3000", "1e3"])("отклоняет PORT=%j", (raw) => {
|
||
expect(() => parsePort(raw)).toThrow("Invalid PORT");
|
||
});
|
||
|
||
it("без PORT использует 3000", () => {
|
||
expect(parsePort(undefined)).toBe(3000);
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Проверка здоровья", () => {
|
||
let app: FastifyInstance;
|
||
afterEach(async () => app?.close());
|
||
|
||
it("Scenario: Сервис здоров", async () => {
|
||
app = await buildApp();
|
||
const res = await app.inject({ method: "GET", url: "/healthz" });
|
||
expect(res.statusCode).toBe(200);
|
||
expect(res.json()).toEqual({ status: "ok" });
|
||
});
|
||
|
||
it("Scenario: Неподдерживаемый метод", async () => {
|
||
app = await buildApp();
|
||
const res = await app.inject({ method: "POST", url: "/healthz", payload: { a: 1 } });
|
||
expect([404, 405]).toContain(res.statusCode);
|
||
expect(res.body).not.toContain(" at ");
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Безопасные ответы об ошибках", () => {
|
||
let app: FastifyInstance;
|
||
afterEach(async () => app?.close());
|
||
|
||
it("Scenario: Неизвестный маршрут", async () => {
|
||
app = await buildApp();
|
||
const res = await app.inject({ method: "GET", url: "/no-such-page" });
|
||
expect(res.statusCode).toBe(404);
|
||
expect(res.json()).toEqual({ error: "not_found" });
|
||
});
|
||
|
||
it("Scenario: Необработанное исключение", async () => {
|
||
app = await buildApp();
|
||
app.get("/boom", async () => {
|
||
throw new Error("db password=secret");
|
||
});
|
||
const res = await app.inject({ method: "GET", url: "/boom" });
|
||
expect(res.statusCode).toBe(500);
|
||
expect(res.json()).toEqual({ error: "internal_error" });
|
||
expect(res.body).not.toContain("secret");
|
||
expect(res.body).not.toContain("at ");
|
||
});
|
||
|
||
it("битый JSON — 400 без деталей парсера", async () => {
|
||
app = await buildApp();
|
||
app.post("/echo", async (req) => req.body);
|
||
const res = await app.inject({
|
||
method: "POST",
|
||
url: "/echo",
|
||
headers: { "content-type": "application/json" },
|
||
payload: '{"a":',
|
||
});
|
||
expect(res.statusCode).toBe(400);
|
||
expect(res.json()).toEqual({ error: "bad_request" });
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Заголовки безопасности и лимит тела", () => {
|
||
let app: FastifyInstance;
|
||
afterEach(async () => app?.close());
|
||
|
||
it("Scenario: Заголовки на главной", async () => {
|
||
app = await buildApp();
|
||
const res = await app.inject({ method: "GET", url: "/" });
|
||
expect(res.headers["x-content-type-options"]).toBe("nosniff");
|
||
expect(res.headers["content-security-policy"]).toContain("default-src 'self'");
|
||
expect(res.headers["content-security-policy"]).toContain("frame-ancestors 'none'");
|
||
expect(res.headers["x-frame-options"]).toBe("DENY");
|
||
expect(res.headers["referrer-policy"]).toBeDefined();
|
||
expect(res.headers["x-powered-by"]).toBeUndefined();
|
||
});
|
||
|
||
it("заголовки есть и на ответах об ошибках", async () => {
|
||
app = await buildApp();
|
||
const res = await app.inject({ method: "GET", url: "/no-such-page" });
|
||
expect(res.headers["x-content-type-options"]).toBe("nosniff");
|
||
});
|
||
|
||
it("Scenario: Слишком большое тело", async () => {
|
||
app = await buildApp();
|
||
const payload = JSON.stringify({ data: "x".repeat(2 * 1024 * 1024) });
|
||
const res = await app.inject({
|
||
method: "POST",
|
||
url: "/healthz",
|
||
headers: { "content-type": "application/json" },
|
||
payload,
|
||
});
|
||
expect(res.statusCode).toBe(413);
|
||
});
|
||
|
||
it("слишком большое тело на существующем POST-маршруте — 413", async () => {
|
||
app = await buildApp();
|
||
app.post("/echo", async () => ({ ok: true }));
|
||
const res = await app.inject({
|
||
method: "POST",
|
||
url: "/echo",
|
||
headers: { "content-type": "application/json" },
|
||
payload: JSON.stringify({ data: "x".repeat(2 * 1024 * 1024) }),
|
||
});
|
||
expect(res.statusCode).toBe(413);
|
||
expect(res.json()).toEqual({ error: "payload_too_large" });
|
||
});
|
||
});
|