Add ARCHITECTURE.md (layers, flows, folder map, glossary), CONTRIBUTING.md (setup and step-by-step recipes) and a README in each main folder, with an index of docs/. Convert the 511 JavaScript headers from "// Rôle :" lines to JSDoc @file blocks, define a three-level header template in website/AGENTS.md and check the header in tests/file-headers.test.mjs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
373 lines
17 KiB
JavaScript
373 lines
17 KiB
JavaScript
/**
|
|
* @file Vérifie le contrat HTTP de l'envoi de toolbox, l'usage unique, l'expiration et chaque plafond qui
|
|
* protège le serveur.
|
|
*/
|
|
|
|
import assert from "node:assert/strict";
|
|
import { existsSync, readdirSync } from "node:fs";
|
|
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
import { get as httpGet } from "node:http";
|
|
import { connect } from "node:net";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { test } from "node:test";
|
|
import { createSharesApi, createStaticServer } from "../server.mjs";
|
|
import { SHARE_MAX_BYTES, SHARE_TTL_MS, createSharesApiHandler } from "../services/shares/api.js";
|
|
|
|
const TB = 1024 ** 4;
|
|
// Les refus attendus sont journalisés par le service : ils ne doivent pas encombrer la sortie des tests.
|
|
console.warn = () => {};
|
|
|
|
function payload(size = 256, fill = 7) {
|
|
const bytes = Buffer.alloc(size, fill);
|
|
bytes.write("SKS1", 0, "latin1");
|
|
return bytes;
|
|
}
|
|
|
|
async function setup(t, options = {}) {
|
|
const root = await mkdtemp(join(tmpdir(), "sokko-shares-root-"));
|
|
const dir = options.dir || await mkdtemp(join(tmpdir(), "sokko-shares-"));
|
|
await writeFile(join(root, "index.html"), "<main>Sokko G</main>");
|
|
const clock = { value: Date.UTC(2026, 10, 11, 12) };
|
|
const sharesApi = createSharesApiHandler({
|
|
enabled: true,
|
|
dir,
|
|
env: { NODE_ENV: "test" },
|
|
now: () => clock.value,
|
|
statfs: options.statfs || (async () => ({ bavail: TB, bsize: 1 })),
|
|
limits: options.limits || {}
|
|
});
|
|
const server = createStaticServer({ root, publicRoot: root, sharesApi });
|
|
await new Promise((resolvePromise) => server.listen(0, "127.0.0.1", resolvePromise));
|
|
const base = `http://127.0.0.1:${server.address().port}`;
|
|
t.after(async () => {
|
|
server.closeAllConnections();
|
|
await new Promise((resolvePromise) => server.close(resolvePromise));
|
|
await rm(root, { recursive: true, force: true });
|
|
if (!options.dir) await rm(dir, { recursive: true, force: true });
|
|
});
|
|
return { base, dir, clock, sharesApi, port: server.address().port };
|
|
}
|
|
|
|
function upload(base, body = payload(), { singleUse = false, headers = {} } = {}) {
|
|
return fetch(`${base}/api/shares`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/octet-stream", "X-Sokkog-Share": "1", ...(singleUse ? { "X-Share-Single-Use": "1" } : {}), ...headers },
|
|
body
|
|
});
|
|
}
|
|
|
|
async function created(base, body, options) {
|
|
const response = await upload(base, body, options);
|
|
assert.equal(response.status, 201, await response.clone().text());
|
|
return response.json();
|
|
}
|
|
|
|
async function download(base, id) {
|
|
const response = await fetch(`${base}/api/shares/${id}`);
|
|
return { status: response.status, headers: response.headers, body: Buffer.from(await response.arrayBuffer()) };
|
|
}
|
|
|
|
// Envoie les en-têtes et une partie du corps à la main, pour simuler un client lent ou interrompu.
|
|
function rawUpload(port, { declared, sent = Buffer.alloc(0) }) {
|
|
const socket = connect(port, "127.0.0.1");
|
|
const response = new Promise((resolvePromise) => {
|
|
let data = "";
|
|
socket.on("data", (chunk) => { data += chunk; });
|
|
socket.on("close", () => resolvePromise(data.split("\r\n")[0]));
|
|
socket.on("error", () => {});
|
|
});
|
|
socket.write(`POST /api/shares HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/octet-stream\r\nX-Sokkog-Share: 1\r\nContent-Length: ${declared}\r\n\r\n`);
|
|
if (sent.length) socket.write(sent);
|
|
return { socket, response };
|
|
}
|
|
|
|
function waitFor(predicate, timeoutMs = 3000) {
|
|
const started = Date.now();
|
|
return new Promise((resolvePromise, reject) => {
|
|
const tick = () => {
|
|
if (predicate()) return resolvePromise();
|
|
if (Date.now() - started > timeoutMs) return reject(new Error("condition not reached"));
|
|
setTimeout(tick, 10);
|
|
};
|
|
tick();
|
|
});
|
|
}
|
|
|
|
const partFiles = (dir) => readdirSync(dir).filter((name) => name.endsWith(".part"));
|
|
|
|
test("config reports whether sharing is enabled", async (t) => {
|
|
const { base } = await setup(t);
|
|
assert.deepEqual(await (await fetch(`${base}/api/shares/config`)).json(), { enabled: true, maxBytes: SHARE_MAX_BYTES, ttlMs: SHARE_TTL_MS });
|
|
|
|
const disabled = createSharesApiHandler({ enabled: false, env: {} });
|
|
const server = createStaticServer({ root: tmpdir(), publicRoot: tmpdir(), sharesApi: disabled });
|
|
await new Promise((resolvePromise) => server.listen(0, "127.0.0.1", resolvePromise));
|
|
t.after(() => new Promise((resolvePromise) => server.close(resolvePromise)));
|
|
const disabledBase = `http://127.0.0.1:${server.address().port}`;
|
|
assert.equal((await (await fetch(`${disabledBase}/api/shares/config`)).json()).enabled, false);
|
|
const refused = await upload(disabledBase);
|
|
assert.equal(refused.status, 503);
|
|
assert.equal((await refused.json()).error.code, "SHARES_DISABLED");
|
|
});
|
|
|
|
test("a reusable share can be read several times and revoked with its token only", async (t) => {
|
|
const { base } = await setup(t);
|
|
const body = payload(4096, 3);
|
|
const share = await created(base, body);
|
|
assert.match(share.id, /^[A-Za-z0-9_-]{22}$/);
|
|
assert.equal(share.singleUse, false);
|
|
|
|
const meta = await (await fetch(`${base}/api/shares/${share.id}/meta`)).json();
|
|
assert.deepEqual(meta, { size: body.length, expiresAt: share.expiresAt, singleUse: false });
|
|
for (let index = 0; index < 2; index += 1) {
|
|
const read = await download(base, share.id);
|
|
assert.equal(read.status, 200);
|
|
assert.equal(read.headers.get("cache-control"), "no-store");
|
|
assert.equal(read.headers.get("x-share-expires-at"), String(share.expiresAt));
|
|
assert.deepEqual(read.body, body);
|
|
}
|
|
|
|
const wrong = await fetch(`${base}/api/shares/${share.id}`, { method: "DELETE", headers: { "X-Share-Delete-Token": "nope" } });
|
|
assert.equal(wrong.status, 403);
|
|
const revoked = await fetch(`${base}/api/shares/${share.id}`, { method: "DELETE", headers: { "X-Share-Delete-Token": share.deleteToken } });
|
|
assert.equal(revoked.status, 204);
|
|
assert.equal((await download(base, share.id)).status, 404);
|
|
assert.equal((await fetch(`${base}/api/shares/${share.id}/meta`)).status, 404);
|
|
});
|
|
|
|
test("a single-use share is deleted once fully read, and meta does not consume it", async (t) => {
|
|
const { base, dir } = await setup(t);
|
|
const share = await created(base, payload(), { singleUse: true });
|
|
assert.equal(share.singleUse, true);
|
|
assert.equal((await fetch(`${base}/api/shares/${share.id}/meta`)).status, 200);
|
|
assert.equal((await fetch(`${base}/api/shares/${share.id}/meta`)).status, 200);
|
|
|
|
const first = await download(base, share.id);
|
|
assert.equal(first.status, 200);
|
|
assert.equal(first.headers.get("x-share-single-use"), "1");
|
|
const second = await download(base, share.id);
|
|
assert.equal(second.status, 404);
|
|
assert.equal(JSON.parse(second.body).error.code, "SHARE_NOT_FOUND");
|
|
await waitFor(() => !existsSync(join(dir, `${share.id}.bin`)) && !existsSync(join(dir, `${share.id}.json`)));
|
|
});
|
|
|
|
test("a single-use share stays available after an interrupted read and refuses a concurrent one", async (t) => {
|
|
const { base, port } = await setup(t);
|
|
const body = payload(16 * 1024 * 1024, 9);
|
|
const share = await created(base, body, { singleUse: true });
|
|
|
|
// La première lecture reste ouverte sans être consommée : une seconde lecture simultanée est refusée.
|
|
const pending = await new Promise((resolvePromise) => {
|
|
const request = httpGet({ host: "127.0.0.1", port, path: `/api/shares/${share.id}` }, (response) => {
|
|
response.pause();
|
|
resolvePromise({ request, response });
|
|
});
|
|
});
|
|
assert.equal(pending.response.statusCode, 200);
|
|
assert.equal((await download(base, share.id)).status, 404);
|
|
|
|
pending.request.destroy();
|
|
let read = null;
|
|
for (let attempt = 0; attempt < 50 && read?.status !== 200; attempt += 1) {
|
|
await new Promise((resolvePromise) => setTimeout(resolvePromise, 20));
|
|
read = await download(base, share.id);
|
|
}
|
|
assert.equal(read.status, 200);
|
|
assert.equal(read.body.length, body.length);
|
|
assert.equal((await download(base, share.id)).status, 404);
|
|
});
|
|
|
|
test("uploads are validated before anything is stored", async (t) => {
|
|
const { base, dir, port } = await setup(t);
|
|
const missingHeader = await fetch(`${base}/api/shares`, { method: "POST", headers: { "Content-Type": "application/octet-stream" }, body: payload() });
|
|
assert.equal(missingHeader.status, 400);
|
|
assert.equal((await missingHeader.json()).error.code, "SHARE_HEADER_REQUIRED");
|
|
assert.equal((await upload(base, payload(), { headers: { "Content-Type": "application/json" } })).status, 415);
|
|
|
|
const badMagic = await upload(base, Buffer.alloc(256, 1));
|
|
assert.equal(badMagic.status, 400);
|
|
assert.equal((await badMagic.json()).error.code, "SHARE_FORMAT");
|
|
assert.equal((await upload(base, payload(8))).status, 400);
|
|
|
|
const tooLarge = rawUpload(port, { declared: SHARE_MAX_BYTES + 1 });
|
|
assert.match(await tooLarge.response, / 413 /);
|
|
|
|
const aborted = rawUpload(port, { declared: 4096, sent: payload(1024) });
|
|
await waitFor(() => partFiles(dir).length === 1);
|
|
aborted.socket.destroy();
|
|
await waitFor(() => partFiles(dir).length === 0);
|
|
assert.deepEqual(readdirSync(dir), []);
|
|
|
|
assert.equal((await fetch(`${base}/api/shares/short`)).status, 400);
|
|
assert.equal((await fetch(`${base}/api/shares/..%2F..%2Fetc%2Fpasswd`)).status, 400);
|
|
assert.equal((await fetch(`${base}/api/shares/${"a".repeat(22)}`)).status, 404);
|
|
assert.equal((await fetch(`${base}/api/shares`)).status, 405);
|
|
});
|
|
|
|
test("shares expire after 24 hours and are purged from disk", async (t) => {
|
|
const { base, dir, clock, sharesApi } = await setup(t);
|
|
const share = await created(base, payload());
|
|
clock.value += SHARE_TTL_MS - 1;
|
|
assert.equal((await download(base, share.id)).status, 200);
|
|
clock.value += 1;
|
|
assert.equal((await download(base, share.id)).status, 404);
|
|
assert.equal((await fetch(`${base}/api/shares/${share.id}`, { method: "DELETE", headers: { "X-Share-Delete-Token": share.deleteToken } })).status, 404);
|
|
|
|
const other = await created(base, payload());
|
|
clock.value += SHARE_TTL_MS;
|
|
await sharesApi.store.purge();
|
|
assert.equal(existsSync(join(dir, `${other.id}.bin`)), false);
|
|
assert.equal(sharesApi.store.totalBytes, 0);
|
|
});
|
|
|
|
test("a restart keeps valid shares and drops expired, partial and orphan files", async (t) => {
|
|
const dir = await mkdtemp(join(tmpdir(), "sokko-shares-restart-"));
|
|
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
const first = await setup(t, { dir });
|
|
const kept = await created(first.base, payload(300));
|
|
await writeFile(join(dir, `${"b".repeat(22)}.part`), "partial");
|
|
await writeFile(join(dir, `${"c".repeat(22)}.bin`), "orphan");
|
|
|
|
const reloaded = createSharesApiHandler({ enabled: true, dir, env: {}, now: () => first.clock.value });
|
|
t.after(reloaded.close);
|
|
assert.equal(reloaded.store.count, 1);
|
|
assert.equal(reloaded.store.totalBytes, 300);
|
|
assert.deepEqual(readdirSync(dir).sort(), [`${kept.id}.bin`, `${kept.id}.json`].sort());
|
|
|
|
const later = createSharesApiHandler({ enabled: true, dir, env: {}, now: () => first.clock.value + SHARE_TTL_MS });
|
|
t.after(later.close);
|
|
assert.equal(later.store.count, 0);
|
|
assert.deepEqual(readdirSync(dir), []);
|
|
});
|
|
|
|
test("total storage, share count and free disk space are capped", async (t) => {
|
|
const { base } = await setup(t, { limits: { maxTotalBytes: 600 } });
|
|
await created(base, payload(400));
|
|
const full = await upload(base, payload(400));
|
|
assert.equal(full.status, 507);
|
|
assert.equal((await full.json()).error.code, "SHARE_STORAGE_FULL");
|
|
await created(base, payload(200));
|
|
|
|
const count = await setup(t, { limits: { maxActiveShares: 1 } });
|
|
await created(count.base, payload());
|
|
assert.equal((await upload(count.base, payload())).status, 507);
|
|
|
|
const disk = await setup(t, { statfs: async () => ({ bavail: 1000, bsize: 1024 }), limits: { minFreeBytes: 1000 * 1024 - 100 } });
|
|
assert.equal((await upload(disk.base, payload(50))).status, 201);
|
|
assert.equal((await upload(disk.base, payload(200))).status, 507);
|
|
});
|
|
|
|
test("the daily volume is capped for the whole service and per connection", async (t) => {
|
|
const global = await setup(t, { limits: { dailyBytes: 500 } });
|
|
await created(global.base, payload(300));
|
|
const refused = await upload(global.base, payload(300));
|
|
assert.equal(refused.status, 429);
|
|
assert.equal((await refused.json()).error.code, "SHARE_DAILY_QUOTA");
|
|
global.clock.value += 24 * 60 * 60 * 1000 + 60 * 60 * 1000;
|
|
assert.equal((await upload(global.base, payload(300))).status, 201);
|
|
|
|
const perIp = await setup(t, { limits: { ipDailyUploads: 2 } });
|
|
await created(perIp.base, payload());
|
|
await created(perIp.base, payload());
|
|
const third = await upload(perIp.base, payload());
|
|
assert.equal(third.status, 429);
|
|
assert.equal((await third.json()).error.code, "SHARE_IP_QUOTA");
|
|
// Une autre connexion, derrière le proxy, garde son propre compteur.
|
|
assert.equal((await upload(perIp.base, payload(), { headers: { "X-Forwarded-For": "203.0.113.9" } })).status, 201);
|
|
|
|
const bytes = await setup(t, { limits: { ipDailyBytes: 500 } });
|
|
await created(bytes.base, payload(300));
|
|
assert.equal((await upload(bytes.base, payload(300))).status, 429);
|
|
|
|
const minute = await setup(t, { limits: { ipUploadsPerMinute: 1 } });
|
|
await created(minute.base, payload());
|
|
assert.equal((await upload(minute.base, payload())).status, 429);
|
|
});
|
|
|
|
test("concurrent uploads are capped and a stalled upload is cut off", async (t) => {
|
|
const { base, dir, port } = await setup(t, { limits: { maxConcurrentUploads: 1, uploadIdleTimeoutMs: 200 } });
|
|
const stalled = rawUpload(port, { declared: 4096, sent: payload(512) });
|
|
await waitFor(() => partFiles(dir).length === 1);
|
|
const busy = await upload(base, payload());
|
|
assert.equal(busy.status, 503);
|
|
assert.equal(busy.headers.get("retry-after"), "30");
|
|
assert.match(await stalled.response, / 408 /);
|
|
await waitFor(() => partFiles(dir).length === 0);
|
|
assert.equal((await upload(base, payload())).status, 201);
|
|
});
|
|
|
|
// Toutes les vérifications attendent ensemble le disque : sans réservation préalable, chacune validerait la même place.
|
|
test("simultaneous uploads cannot share the last slot while the disk check is pending", async (t) => {
|
|
// Le disque ne répond qu'une fois les trois requêtes arrivées : chacune attend sa vérification ou a déjà été refusée.
|
|
let waiting = 0;
|
|
let refused = 0;
|
|
let openDisk;
|
|
let diskOpen;
|
|
const statfs = async () => {
|
|
waiting += 1;
|
|
await diskOpen;
|
|
return { bavail: TB, bsize: 1 };
|
|
};
|
|
const warn = console.warn;
|
|
console.warn = (message) => { if (String(message).startsWith("Toolbox share refused")) refused += 1; };
|
|
t.after(() => { console.warn = warn; });
|
|
const releaseDiskChecks = async (count) => {
|
|
await waitFor(() => waiting + refused >= count);
|
|
openDisk();
|
|
};
|
|
|
|
const cases = [
|
|
{ limits: { maxConcurrentUploads: 1 }, code: "SHARE_BUSY" },
|
|
{ limits: { maxActiveShares: 1 }, code: "SHARE_STORAGE_FULL" },
|
|
{ limits: { maxTotalBytes: 300 }, code: "SHARE_STORAGE_FULL" },
|
|
{ limits: { dailyBytes: 300 }, code: "SHARE_DAILY_QUOTA" },
|
|
{ limits: { ipDailyUploads: 1 }, code: "SHARE_IP_QUOTA" },
|
|
{ limits: { ipDailyBytes: 300 }, code: "SHARE_IP_QUOTA" }
|
|
];
|
|
for (const { limits, code } of cases) {
|
|
const { base, sharesApi } = await setup(t, { statfs, limits });
|
|
waiting = 0;
|
|
refused = 0;
|
|
diskOpen = new Promise((resolvePromise) => { openDisk = resolvePromise; });
|
|
const responses = [upload(base, payload(256)), upload(base, payload(256)), upload(base, payload(256))];
|
|
await releaseDiskChecks(3);
|
|
const statuses = await Promise.all(responses.map(async (response) => {
|
|
const result = await response;
|
|
return { status: result.status, code: (await result.json()).error?.code };
|
|
}));
|
|
assert.equal(statuses.filter(({ status }) => status === 201).length, 1, `${JSON.stringify(limits)}: ${JSON.stringify(statuses)}`);
|
|
assert.ok(statuses.filter(({ status }) => status !== 201).every((entry) => entry.code === code), `${JSON.stringify(limits)}: ${JSON.stringify(statuses)}`);
|
|
assert.equal(sharesApi.store.count, 1);
|
|
}
|
|
});
|
|
|
|
test("a refused disk check releases its reservation", async (t) => {
|
|
let free = 0;
|
|
const { base } = await setup(t, { statfs: async () => ({ bavail: free, bsize: 1 }), limits: { maxConcurrentUploads: 1, minFreeBytes: 1000 } });
|
|
assert.equal((await upload(base, payload())).status, 507);
|
|
free = TB;
|
|
assert.equal((await upload(base, payload())).status, 201);
|
|
});
|
|
|
|
test("a reusable share stops answering after its maximum number of reads", async (t) => {
|
|
const { base } = await setup(t, { limits: { maxReads: 2 } });
|
|
const share = await created(base, payload());
|
|
assert.equal((await download(base, share.id)).status, 200);
|
|
assert.equal((await download(base, share.id)).status, 200);
|
|
assert.equal((await download(base, share.id)).status, 404);
|
|
assert.equal((await fetch(`${base}/api/shares/${share.id}/meta`)).status, 404);
|
|
});
|
|
|
|
test("production requires an explicit directory, and an invalid configuration only disables sharing", () => {
|
|
assert.throws(() => createSharesApiHandler({ enabled: true, env: { NODE_ENV: "production" } }), /SHARES_DIR/);
|
|
assert.throws(() => createSharesApiHandler({ enabled: true, dir: tmpdir(), env: { SHARES_MAX_TOTAL_BYTES: "lots" } }), /SHARES_MAX_TOTAL_BYTES/);
|
|
const originalError = console.error;
|
|
console.error = () => {};
|
|
try {
|
|
const fallback = createSharesApi({ enabled: true, env: { NODE_ENV: "production" } });
|
|
assert.equal(fallback.store, null);
|
|
} finally {
|
|
console.error = originalError;
|
|
}
|
|
});
|