feat(security): harden HTTP, storage, status reading and launches
- security headers on every response (strict CSP, nosniff, frame DENY, no-referrer, HSTS behind TLS proxy) and no x-powered-by; hero image set through the CSSOM so the CSP needs no inline styles - error handler: 400 without stack trace for malformed URLs/JSON and multer errors, 500 logged in full - image uploads: type detected from the file signature (PNG/JPEG/WebP), not the client MIME type; multer part limits - storage: atomic JSON writes (tmp + rename) with mode 600, dirs 700; refuse to start when groups.json is corrupted instead of recreating admin; initial admin password written to a 600 file instead of the logs - status file read asynchronously in the background and cached, one read at a time with a 3 s timeout, so a hung NFS mount never blocks requests; cleanup refused when the status is stale or empty - launches: 10 min cooldown after a successful start (status lags behind), ssh BatchMode/ConnectTimeout/IdentitiesOnly, remote stdout/stderr kept in the server log instead of the API response Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
7d89a4e646
commit
d74f80fbf9
16 changed files with 401 additions and 45 deletions
|
|
@ -13,6 +13,8 @@ const { createApp } = await import("../src/app.js");
|
|||
const { hashPassword } = await import("../src/services/crypto.js");
|
||||
const { pruneLogs } = await import("../src/services/storage.js");
|
||||
const { resetLoginThrottle } = await import("../src/services/loginThrottle.js");
|
||||
const { refreshStatus } = await import("../src/services/status.js");
|
||||
const { resetLaunchGuard } = await import("../src/services/launchGuard.js");
|
||||
|
||||
const servers = [
|
||||
{
|
||||
|
|
@ -34,6 +36,11 @@ const servers = [
|
|||
];
|
||||
|
||||
const adminLoginPassword = "admin-password";
|
||||
// Signature PNG suivie de quelques octets: suffisant pour la detection du format.
|
||||
const PNG_BYTES = Buffer.concat([
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
||||
Buffer.from("fake-png-body"),
|
||||
]);
|
||||
const playerPassword = "player-password";
|
||||
|
||||
fs.writeFileSync(
|
||||
|
|
@ -84,6 +91,8 @@ fs.writeFileSync(
|
|||
fs.writeFileSync(path.join(tmpRoot, "launch-logs.json"), "[]\n");
|
||||
fs.writeFileSync(path.join(tmpRoot, "server-images.json"), "{}\n");
|
||||
|
||||
await refreshStatus();
|
||||
|
||||
const app = createApp();
|
||||
const server = app.listen(0);
|
||||
await new Promise((resolve) => server.once("listening", resolve));
|
||||
|
|
@ -173,6 +182,8 @@ test("status file is authoritative for server list and names", async () => {
|
|||
)}\n`
|
||||
);
|
||||
|
||||
await refreshStatus();
|
||||
|
||||
const token = await login(adminLoginPassword);
|
||||
const response = await request("/api/servers", { token });
|
||||
const names = response.body.servers.map((server) => server.game);
|
||||
|
|
@ -184,6 +195,7 @@ test("status file is authoritative for server list and names", async () => {
|
|||
assert.equal(response.body.servers[1].canStart, false);
|
||||
|
||||
fs.writeFileSync(process.env.GAMESERVERS_STATUS_FILE, originalStatus);
|
||||
await refreshStatus();
|
||||
});
|
||||
|
||||
test("starts an offline authorized server and writes a log", async () => {
|
||||
|
|
@ -228,8 +240,11 @@ test("starts an offline authorized server and writes a log", async () => {
|
|||
assert.equal(logs.status, 200);
|
||||
assert.equal(logs.body.logs[0].groupId, "players");
|
||||
assert.equal(logs.body.logs[0].serverId, "offline-server");
|
||||
assert.equal(start.body.stdout, undefined);
|
||||
} finally {
|
||||
fs.writeFileSync(process.env.GAMESERVERS_STATUS_FILE, originalStatus);
|
||||
await refreshStatus();
|
||||
resetLaunchGuard();
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -307,7 +322,7 @@ test("admin can upload and delete a server image", async () => {
|
|||
const formData = new FormData();
|
||||
formData.set(
|
||||
"image",
|
||||
new Blob([Buffer.from("fake-image")], { type: "image/png" }),
|
||||
new Blob([PNG_BYTES], { type: "image/png" }),
|
||||
"server.png"
|
||||
);
|
||||
|
||||
|
|
@ -526,6 +541,70 @@ test("blocks login after too many attempts, even with spoofed X-Forwarded-For",
|
|||
assert.ok(await login(playerPassword));
|
||||
});
|
||||
|
||||
test("rejects uploads whose content is not a real image", async () => {
|
||||
const token = await login(adminLoginPassword);
|
||||
const formData = new FormData();
|
||||
formData.set(
|
||||
"image",
|
||||
new Blob([Buffer.from("<script>alert(1)</script>")], { type: "image/png" }),
|
||||
"evil.png"
|
||||
);
|
||||
|
||||
const uploaded = await request("/api/admin/servers/offline-server/image", {
|
||||
method: "POST",
|
||||
token,
|
||||
body: formData,
|
||||
});
|
||||
assert.equal(uploaded.status, 400);
|
||||
});
|
||||
|
||||
test("blocks a second launch during the cooldown after a successful start", async () => {
|
||||
resetLaunchGuard();
|
||||
try {
|
||||
fs.writeFileSync(
|
||||
process.env.GAMESERVERS_STATUS_FILE,
|
||||
`${JSON.stringify({
|
||||
servers: [
|
||||
{ id: "offline-server", game: "Offline Server", address: "games.example:1111", port: 1111, active: false },
|
||||
{ id: "online-server", game: "Online Server", address: "games.example:2222", port: 2222, active: false },
|
||||
],
|
||||
})}\n`
|
||||
);
|
||||
await refreshStatus();
|
||||
|
||||
const token = await login(adminLoginPassword);
|
||||
const first = await request("/api/servers/offline-server/start", { method: "POST", token });
|
||||
assert.equal(first.status, 200);
|
||||
|
||||
const list = await request("/api/servers", { token });
|
||||
assert.ok(list.body.servers.every((entry) => entry.canStart === false));
|
||||
|
||||
const second = await request("/api/servers/offline-server/start", { method: "POST", token });
|
||||
assert.equal(second.status, 409);
|
||||
} finally {
|
||||
fs.writeFileSync(process.env.GAMESERVERS_STATUS_FILE, originalStatus);
|
||||
await refreshStatus();
|
||||
resetLaunchGuard();
|
||||
}
|
||||
});
|
||||
|
||||
test("sends security headers and hides x-powered-by", async () => {
|
||||
const response = await fetch(`${baseUrl}/`);
|
||||
assert.equal(response.status, 200);
|
||||
assert.match(response.headers.get("content-security-policy"), /script-src 'self'/);
|
||||
assert.equal(response.headers.get("x-content-type-options"), "nosniff");
|
||||
assert.equal(response.headers.get("x-frame-options"), "DENY");
|
||||
assert.equal(response.headers.get("x-powered-by"), null);
|
||||
});
|
||||
|
||||
test("answers 400 without a stack trace to malformed URLs", async () => {
|
||||
const response = await fetch(`${baseUrl}/api/servers/%E0%A4%A/start`, { method: "POST" });
|
||||
assert.ok(response.status === 400 || response.status === 401);
|
||||
const malformedPage = await fetch(`${baseUrl}/%E0%A4%A`);
|
||||
assert.equal(malformedPage.status, 400);
|
||||
assert.doesNotMatch(await malformedPage.text(), /at decodeURIComponent|URIError/);
|
||||
});
|
||||
|
||||
async function login(password) {
|
||||
const response = await request("/api/login", {
|
||||
method: "POST",
|
||||
|
|
|
|||
|
|
@ -11,10 +11,16 @@ test("builds ssh args with optional port and key file", () => {
|
|||
command: "bash /opt/game/start.sh",
|
||||
}),
|
||||
[
|
||||
"-o",
|
||||
"BatchMode=yes",
|
||||
"-o",
|
||||
"ConnectTimeout=10",
|
||||
"-p",
|
||||
"2222",
|
||||
"-i",
|
||||
"/home/app/.ssh/game-key",
|
||||
"-o",
|
||||
"IdentitiesOnly=yes",
|
||||
"user@192.0.2.10",
|
||||
"bash /opt/game/start.sh",
|
||||
]
|
||||
|
|
@ -29,6 +35,6 @@ test("builds ssh args without optional port and key file", () => {
|
|||
keyFile: "",
|
||||
command: "bash /opt/game/start.sh",
|
||||
}),
|
||||
["game-server", "bash /opt/game/start.sh"]
|
||||
["-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "game-server", "bash /opt/game/start.sh"]
|
||||
);
|
||||
});
|
||||
|
|
|
|||
54
test/storage.test.js
Normal file
54
test/storage.test.js
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { execFile } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const storageModule = new URL("../src/services/storage.js", import.meta.url).href;
|
||||
|
||||
// Chaque cas tourne dans un processus a part: la config (STORAGE_DIR) est lue a l'import.
|
||||
async function runEnsureStorageLayout(storageDir) {
|
||||
return execFileAsync(
|
||||
process.execPath,
|
||||
[
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
`const m = await import(${JSON.stringify(storageModule)}); await m.ensureStorageLayout();`,
|
||||
],
|
||||
{ env: { ...process.env, STORAGE_DIR: storageDir } }
|
||||
);
|
||||
}
|
||||
|
||||
function mode(file) {
|
||||
return fs.statSync(file).mode & 0o777;
|
||||
}
|
||||
|
||||
test("first start writes private files and the admin password to a file, not the logs", async () => {
|
||||
const storageDir = fs.mkdtempSync(path.join(os.tmpdir(), "gsc-storage-"));
|
||||
const { stdout } = await runEnsureStorageLayout(storageDir);
|
||||
|
||||
const passwordFile = path.join(storageDir, "initial-admin-password.txt");
|
||||
const password = fs.readFileSync(passwordFile, "utf8").trim();
|
||||
assert.ok(password.length >= 12);
|
||||
assert.equal(stdout.includes(password), false);
|
||||
assert.equal(mode(passwordFile), 0o600);
|
||||
assert.equal(mode(path.join(storageDir, "groups.json")), 0o600);
|
||||
assert.equal(mode(path.join(storageDir, "servers.json")), 0o600);
|
||||
assert.deepEqual(
|
||||
fs.readdirSync(storageDir).filter((name) => name.endsWith(".tmp")),
|
||||
[]
|
||||
);
|
||||
});
|
||||
|
||||
test("refuses to start when groups.json is corrupted instead of recreating admin", async () => {
|
||||
const storageDir = fs.mkdtempSync(path.join(os.tmpdir(), "gsc-storage-"));
|
||||
const groupsFile = path.join(storageDir, "groups.json");
|
||||
fs.writeFileSync(groupsFile, '[{"id": "admin", "passwordHash": ');
|
||||
|
||||
await assert.rejects(runEnsureStorageLayout(storageDir));
|
||||
assert.equal(fs.readFileSync(groupsFile, "utf8"), '[{"id": "admin", "passwordHash": ');
|
||||
assert.equal(fs.existsSync(path.join(storageDir, "initial-admin-password.txt")), false);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue