Keep the Node server alive on invalid requests and Cards failures
An invalid URL or Host header rejected inside the async request handler and ended the process, even with Sokko TCG disabled. Requests now parse against a fixed base and any unexpected failure answers 500. An invalid Cards setup disables the game instead of the site, SIGTERM closes the database cleanly, and the rate limiter forgets past minutes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5ce35cd7ba
commit
d72dd38317
4 changed files with 202 additions and 17 deletions
126
tests/server-robustness.test.mjs
Normal file
126
tests/server-robustness.test.mjs
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
// Rôle : vérifie qu'aucune requête ni erreur de configuration Sokko TCG ne peut interrompre le serveur Node.
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { connect } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { test } from "node:test";
|
||||
import { createCardsApi, createStaticServer } from "../server.mjs";
|
||||
import { createCardsApiHandler, createRateLimiter } from "../services/cards/api.js";
|
||||
|
||||
const projectRoot = resolve(".");
|
||||
const serverFile = join(projectRoot, "server.mjs");
|
||||
|
||||
// `fetch` normalise les URL et les en-têtes : seule une requête brute reproduit ce qu'un client hostile peut envoyer.
|
||||
function rawRequest(port, { target = "/", host = "localhost", extraHeaders = "" }) {
|
||||
return new Promise((resolvePromise, reject) => {
|
||||
const socket = connect(port, "127.0.0.1", () => socket.write(`GET ${target} HTTP/1.1\r\nHost: ${host}\r\n${extraHeaders}Connection: close\r\n\r\n`));
|
||||
let response = "";
|
||||
socket.on("data", (chunk) => { response += chunk; });
|
||||
socket.on("close", () => resolvePromise(response.split("\r\n")[0]));
|
||||
socket.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
async function listen(t, cardsApi) {
|
||||
const root = await mkdtemp(join(tmpdir(), "sokko-server-robustness-"));
|
||||
await writeFile(join(root, "index.html"), "<main>Sokko G</main>");
|
||||
const server = createStaticServer({ root, publicRoot: root, cardsApi });
|
||||
await new Promise((resolvePromise) => server.listen(0, "127.0.0.1", resolvePromise));
|
||||
t.after(async () => {
|
||||
await new Promise((resolvePromise) => server.close(resolvePromise));
|
||||
await rm(root, { recursive: true, force: true });
|
||||
});
|
||||
return server.address().port;
|
||||
}
|
||||
|
||||
const hostileRequests = [
|
||||
["an empty authority in the path", { target: "//" }],
|
||||
["an invalid Host header", { host: "[" }],
|
||||
["an invalid X-Forwarded-Proto header", { extraHeaders: "X-Forwarded-Proto: a b\r\n" }]
|
||||
];
|
||||
|
||||
for (const enabled of [false, true]) {
|
||||
for (const [label, request] of hostileRequests) {
|
||||
test(`${label} leaves the server responding when Sokko TCG is ${enabled ? "enabled" : "disabled"}`, async (t) => {
|
||||
const cardsApi = createCardsApiHandler({ projectRoot, enabled, devAuth: false, databasePath: ":memory:", env: { NODE_ENV: "test" } });
|
||||
const port = await listen(t, cardsApi);
|
||||
const status = await rawRequest(port, request);
|
||||
assert.match(status, /^HTTP\/1\.1 [2-5]\d\d /);
|
||||
assert.match(await rawRequest(port, {}), /^HTTP\/1\.1 200 /);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test("an unexpected API failure answers 500 instead of ending the process", async (t) => {
|
||||
const failingApi = async () => { throw new Error("expected test failure"); };
|
||||
const originalError = console.error;
|
||||
console.error = () => {};
|
||||
t.after(() => { console.error = originalError; });
|
||||
const port = await listen(t, failingApi);
|
||||
assert.match(await rawRequest(port, {}), /^HTTP\/1\.1 500 /);
|
||||
assert.match(await rawRequest(port, {}), /^HTTP\/1\.1 500 /);
|
||||
});
|
||||
|
||||
test("a malformed API path answers 400 and an undecodable foreign cookie is ignored", async (t) => {
|
||||
const cardsApi = createCardsApiHandler({ projectRoot, enabled: true, devAuth: false, databasePath: ":memory:", env: { NODE_ENV: "test" } });
|
||||
const port = await listen(t, cardsApi);
|
||||
const session = cardsApi.service.createSession(cardsApi.service.upsertPlayer({ discordId: "cookie", displayName: "Cookie" }).id);
|
||||
const cookieHeader = `Cookie: foreign=100%; sokkog_cards_session=${session.token}\r\n`;
|
||||
assert.match(await rawRequest(port, { target: "/api/cards/session", extraHeaders: cookieHeader }), /^HTTP\/1\.1 200 /);
|
||||
assert.match(await rawRequest(port, { target: "/api/cards/admin/campaigns/%E0%A4%A", extraHeaders: cookieHeader }), /^HTTP\/1\.1 400 /);
|
||||
});
|
||||
|
||||
test("a Sokko TCG configuration failure disables the game and keeps the site running", async (t) => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "sokko-server-config-"));
|
||||
t.after(() => rm(directory, { recursive: true, force: true }));
|
||||
// Un fichier à la place du dossier parent : la base ne peut pas être créée, comme un dossier non inscriptible.
|
||||
await writeFile(join(directory, "not-a-directory"), "");
|
||||
const logged = [];
|
||||
const originalError = console.error;
|
||||
console.error = (...values) => logged.push(values);
|
||||
t.after(() => { console.error = originalError; });
|
||||
const cardsApi = createCardsApi({ enabled: true, devAuth: false, databasePath: join(directory, "not-a-directory", "cards.sqlite"), env: { NODE_ENV: "test" } });
|
||||
const port = await listen(t, cardsApi);
|
||||
assert.equal(logged.length, 1);
|
||||
assert.match(await rawRequest(port, {}), /^HTTP\/1\.1 200 /);
|
||||
const config = await fetch(`http://127.0.0.1:${port}/api/cards/config`).then((response) => response.json());
|
||||
assert.equal(config.enabled, false);
|
||||
});
|
||||
|
||||
test("SIGTERM closes the database cleanly so no write-ahead log stays behind", async (t) => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "sokko-server-stop-"));
|
||||
t.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const databasePath = join(directory, "cards.sqlite");
|
||||
// Le dossier courant isole le test d'un éventuel .env du projet.
|
||||
const child = spawn(process.execPath, ["--no-warnings", serverFile], {
|
||||
cwd: directory,
|
||||
env: { PATH: process.env.PATH, NODE_ENV: "test", PORT: "0", CARDS_ENABLED: "true", CARDS_DEV_AUTH: "false", CARDS_DB_PATH: databasePath },
|
||||
stdio: ["ignore", "pipe", "pipe"]
|
||||
});
|
||||
t.after(() => child.kill("SIGKILL"));
|
||||
await new Promise((resolvePromise, reject) => {
|
||||
child.stdout.once("data", resolvePromise);
|
||||
child.once("exit", (code) => reject(new Error(`Server exited early with code ${code}.`)));
|
||||
});
|
||||
assert.equal(existsSync(`${databasePath}-wal`), true);
|
||||
const exit = new Promise((resolvePromise) => child.once("exit", (code, signal) => resolvePromise({ code, signal })));
|
||||
child.kill("SIGTERM");
|
||||
assert.deepEqual(await exit, { code: 0, signal: null });
|
||||
assert.equal(existsSync(`${databasePath}-wal`), false);
|
||||
});
|
||||
|
||||
test("the rate limiter forgets past minutes instead of growing without bound", () => {
|
||||
let current = 0;
|
||||
const limiter = createRateLimiter(() => current);
|
||||
const request = (address) => ({ headers: { "x-forwarded-for": address }, socket: {} });
|
||||
for (let index = 0; index < 100; index += 1) limiter(request(`10.0.0.${index}`), "api");
|
||||
assert.equal(limiter.bucketCount(), 100);
|
||||
current = 60_000;
|
||||
limiter(request("10.0.0.1"), "api");
|
||||
assert.equal(limiter.bucketCount(), 1);
|
||||
for (let index = 1; index < 60; index += 1) limiter(request("10.0.0.1"), "api");
|
||||
assert.throws(() => limiter(request("10.0.0.1"), "api"), /Trop de tentatives/);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue