feat: Implement rate limiting, request timeouts, and security headers for improved server protection

This commit is contained in:
2026-10-19 23:15:05 +03:00
parent 7206bf9c4a
commit 85c5baa3e5
8 changed files with 291 additions and 80 deletions

View File

@@ -1,79 +1,15 @@
import { test, before, after } from "node:test";
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFileSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { academicStartYear, todayIso } from "../shared/weeks.js";
import { startApi, fixture } from "./support/nextcloud.js";
// The API over HTTP, as the Android and iOS clients see it: the real server against a stand-in
// for the university's Nextcloud that serves the fixtures as a small catalog.
const SHARE = "/public.php/dav/files/no5zKbMrns6j5jQ/";
const fixture = (name) => readFileSync(new URL(`./fixtures/${name}`, import.meta.url));
const year = academicStartYear(todayIso());
const YEAR = `${year}-${year + 1}`;
const FOLDER = `${SHARE}${YEAR}/Финансово-экономический факультет/Дневная форма/`;
const MODIFIED = "Mon, 14 Sep 2026 13:05:15 GMT";
const files = {
[`${SHARE}Расписание белых и зеленых недель.docx`]: fixture("weeks.docx"),
[`${SHARE}Расписание звонков.docx`]: fixture("bells.docx"),
[`${FOLDER}23-ЛГ_23-БА.docx`]: fixture("fef-23-ba.docx"),
[`${FOLDER}24-ИТ.docx`]: fixture("fit-daily.docx"),
// The university fails on one document and is too slow on another.
[`${FOLDER}Сломанный.docx`]: 500,
[`${FOLDER}Медленный.docx`]: "slow",
};
const folders = [SHARE, `${SHARE}${YEAR}/`, `${SHARE}${YEAR}/Финансово-экономический факультет/`, FOLDER];
const encode = (path) => path.split("/").map(encodeURIComponent).join("/");
const listing = (folder) => {
const children = [...folders.filter((f) => f !== folder && f.startsWith(folder) && !f.slice(folder.length, -1).includes("/")),
...Object.keys(files).filter((f) => f.startsWith(folder) && !f.slice(folder.length).includes("/"))];
const entry = (path) => {
const folder = path.endsWith("/");
const size = Buffer.isBuffer(files[path]) ? files[path].length : 1000;
return `<d:response><d:href>${encode(path)}</d:href><d:propstat><d:prop>${
folder ? "<d:resourcetype><d:collection/></d:resourcetype>" : `<d:resourcetype/><d:getcontentlength>${size}</d:getcontentlength>`
}<d:getlastmodified>${MODIFIED}</d:getlastmodified></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>`;
};
return `<?xml version="1.0"?><d:multistatus xmlns:d="DAV:">${[folder, ...children].map(entry).join("")}</d:multistatus>`;
};
let source, server, base, data;
const stats = { requests: 0, connections: 0 };
let api, base, stats;
before(async () => {
source = createServer((req, res) => {
stats.requests++;
const path = decodeURIComponent(req.url);
if (req.method === "PROPFIND" && folders.includes(path)) {
res.writeHead(207, { "Content-Type": "application/xml" });
return res.end(listing(path));
}
const body = files[path];
if (body === "slow") return setTimeout(() => res.end("late"), 2000);
if (typeof body === "number" || !body) return res.writeHead(body || 404).end();
res.end(body);
});
source.on("connection", () => stats.connections++);
await new Promise((resolve) => source.listen(0, "127.0.0.1", resolve));
data = mkdtempSync(join(tmpdir(), "psu-api-"));
process.env.PSU_SOURCE_ORIGIN = `http://127.0.0.1:${source.address().port}`;
process.env.PSU_DATA_DIR = data;
process.env.PSU_SOURCE_TIMEOUT_MS = "500";
const { app } = await import("../server/index.js");
server = app.listen(0, "127.0.0.1");
await new Promise((resolve) => server.on("listening", resolve));
base = `http://127.0.0.1:${server.address().port}`;
});
after(() => {
server?.close();
server?.closeAllConnections();
source?.closeAllConnections();
source?.close();
rmSync(data, { recursive: true, force: true });
api = await startApi();
({ base, stats } = api);
});
after(() => api?.stop());
const get = (path, headers = {}) => fetch(base + path, { headers });
const json = async (path) => {
@@ -88,6 +24,7 @@ test("API: до загрузки индекса сервер жив, но не
assert.equal(health.status, 200);
assert.equal(health.body.ok, true);
assert.equal(health.body.ready, false);
assert.equal(health.body.client, "127.0.0.1");
assert.equal(typeof health.body.apiVersion, "number");
const ready = await json("/api/ready");
assert.equal(ready.status, 503);

74
test/protect.test.js Normal file
View File

@@ -0,0 +1,74 @@
import { test, before, after } from "node:test";
import assert from "node:assert/strict";
import { existsSync, readFileSync } from "node:fs";
import { createHash } from "node:crypto";
import { startApi } from "./support/nextcloud.js";
// Protection of a server open to the internet, with the limits lowered so the tests reach them:
// five API requests a minute and an 800 ms time limit.
let api, base;
let sent = 0;
before(async () => {
api = await startApi({ PSU_API_RATE_LIMIT: "5", PSU_REQUEST_TIMEOUT_MS: "800", PSU_SOURCE_TIMEOUT_MS: "5000" });
base = api.base;
});
after(() => api?.stop());
const apiGet = (path) => {
sent++;
return fetch(base + path);
};
test("Защита: заголовки безопасности у страницы и API", async () => {
for (const path of ["/", "/api/health"]) {
const response = await fetch(base + path);
await response.arrayBuffer();
const csp = response.headers.get("content-security-policy");
assert.match(csp, /default-src 'self'/, path);
assert.match(csp, /frame-ancestors 'none'/, path);
assert.match(csp, /object-src 'none'/, path);
assert.equal(response.headers.get("x-content-type-options"), "nosniff", path);
assert.equal(response.headers.get("x-frame-options"), "DENY", path);
assert.ok(response.headers.get("referrer-policy"), path);
assert.ok(response.headers.get("permissions-policy"), path);
// Plain HTTP: no HSTS.
assert.equal(response.headers.get("strict-transport-security"), null, path);
}
});
test("Защита: CSP разрешает ровно inline-скрипт темы из собранной страницы", { skip: !existsSync(new URL("../dist/index.html", import.meta.url)) && "нет dist/, сначала npm run build" }, async () => {
const html = readFileSync(new URL("../dist/index.html", import.meta.url), "utf8");
const inline = html.match(/<script>([\s\S]*?)<\/script>/)[1];
const hash = createHash("sha256").update(inline).digest("base64");
const csp = (await fetch(base + "/")).headers.get("content-security-policy");
assert.ok(csp.includes(`'sha256-${hash}'`), csp);
assert.doesNotMatch(csp, /unsafe-inline|unsafe-eval/);
});
test("Защита: запрос, на который сервер не успел ответить, получает 504 timeout", async () => {
const catalog = await (await apiGet("/api/catalog")).json();
const slow = catalog.files.find((f) => f.name === "Медленный.docx");
const started = Date.now();
const response = await apiGet(`/api/original/${slow.id}`);
assert.equal(response.status, 504);
assert.equal((await response.json()).code, "timeout");
assert.equal(response.headers.get("retry-after"), "30");
assert.ok(Date.now() - started < 1800, "ответ не ждёт университет");
// The late answer of the university does not break the server.
await new Promise((resolve) => setTimeout(resolve, 2200));
assert.equal((await fetch(base + "/api/health")).status, 200);
});
test("Защита: лимит запросов к API с одного адреса, проверки здоровья не считаются", async () => {
for (let i = 0; i < 10; i++) {
assert.equal((await fetch(base + "/api/health")).status, 200);
assert.equal((await fetch(base + "/api/ready")).status === 429, false);
}
while (sent < 5) assert.notEqual((await apiGet("/api/nope")).status, 429);
const limited = await apiGet("/api/nope");
assert.equal(limited.status, 429);
assert.equal((await limited.json()).code, "too_many_requests");
assert.ok(Number(limited.headers.get("retry-after")) > 0);
// The page and its files are not API requests and stay available.
assert.equal((await fetch(base + "/")).status, 200);
assert.equal((await fetch(base + "/api/health")).status, 200);
});

81
test/support/nextcloud.js Normal file
View File

@@ -0,0 +1,81 @@
import { createServer } from "node:http";
import { readFileSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { academicStartYear, todayIso } from "../../shared/weeks.js";
// A stand-in for the university's Nextcloud that serves the fixtures as a small catalog, and the
// real API server started against it with a temporary data folder.
export const SHARE = "/public.php/dav/files/no5zKbMrns6j5jQ/";
export const fixture = (name) => readFileSync(new URL(`../fixtures/${name}`, import.meta.url));
const year = academicStartYear(todayIso());
const YEAR = `${year}-${year + 1}`;
const FOLDER = `${SHARE}${YEAR}/Финансово-экономический факультет/Дневная форма/`;
const MODIFIED = "Mon, 14 Sep 2026 13:05:15 GMT";
const files = {
[`${SHARE}Расписание белых и зеленых недель.docx`]: fixture("weeks.docx"),
[`${SHARE}Расписание звонков.docx`]: fixture("bells.docx"),
[`${FOLDER}23-ЛГ_23-БА.docx`]: fixture("fef-23-ba.docx"),
[`${FOLDER}24-ИТ.docx`]: fixture("fit-daily.docx"),
// The university fails on one document and is too slow on another.
[`${FOLDER}Сломанный.docx`]: 500,
[`${FOLDER}Медленный.docx`]: "slow",
};
const folders = [SHARE, `${SHARE}${YEAR}/`, `${SHARE}${YEAR}/Финансово-экономический факультет/`, FOLDER];
const encode = (path) => path.split("/").map(encodeURIComponent).join("/");
const listing = (folder) => {
const children = [...folders.filter((f) => f !== folder && f.startsWith(folder) && !f.slice(folder.length, -1).includes("/")),
...Object.keys(files).filter((f) => f.startsWith(folder) && !f.slice(folder.length).includes("/"))];
const entry = (path) => {
const folder = path.endsWith("/");
const size = Buffer.isBuffer(files[path]) ? files[path].length : 1000;
return `<d:response><d:href>${encode(path)}</d:href><d:propstat><d:prop>${
folder ? "<d:resourcetype><d:collection/></d:resourcetype>" : `<d:resourcetype/><d:getcontentlength>${size}</d:getcontentlength>`
}<d:getlastmodified>${MODIFIED}</d:getlastmodified></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>`;
};
return `<?xml version="1.0"?><d:multistatus xmlns:d="DAV:">${[folder, ...children].map(entry).join("")}</d:multistatus>`;
};
/**
* Starts the stand-in and the API server; `env` adds settings such as lower limits.
* Returns the server's base URL, request statistics of the stand-in and `stop()`.
*/
export async function startApi(env = {}) {
const stats = { requests: 0, connections: 0 };
const source = createServer((req, res) => {
stats.requests++;
const path = decodeURIComponent(req.url);
if (req.method === "PROPFIND" && folders.includes(path)) {
res.writeHead(207, { "Content-Type": "application/xml" });
return res.end(listing(path));
}
const body = files[path];
if (body === "slow") return setTimeout(() => res.end("late"), 2000);
if (typeof body === "number" || !body) return res.writeHead(body || 404).end();
res.end(body);
});
source.on("connection", () => stats.connections++);
await new Promise((resolve) => source.listen(0, "127.0.0.1", resolve));
const data = mkdtempSync(join(tmpdir(), "psu-api-"));
Object.assign(process.env, {
PSU_SOURCE_ORIGIN: `http://127.0.0.1:${source.address().port}`,
PSU_DATA_DIR: data,
PSU_SOURCE_TIMEOUT_MS: "500",
...env,
});
const { app } = await import("../../server/index.js");
const server = app.listen(0, "127.0.0.1");
await new Promise((resolve) => server.on("listening", resolve));
return {
base: `http://127.0.0.1:${server.address().port}`,
stats,
stop() {
server.close();
server.closeAllConnections();
source.closeAllConnections();
source.close();
rmSync(data, { recursive: true, force: true });
},
};
}