Tests du serveur : relais, quotas, IP réelle, OAuth sans état, MCP, site

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pierre MARTIN
2026-11-18 05:10:31 +01:00
co-authored by Claude Opus 5.5
parent 508bab9a8e
commit 91ee787ba0
5 changed files with 748 additions and 0 deletions
+146
View File
@@ -0,0 +1,146 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createRelay } from "../../server/relay.js";
import { clientIp, createRateLimiter } from "../../server/rate-limit.js";
import { startServer, push, auth } from "./helpers.js";
const ID = "ZgJsF_SV8W3E27y5p0AhMg";
const TOKEN = "_NaCNrXbQlORkPj77TOhUThrbXoF740wNVYw9Djg8Z0";
const blob = (/** @type {number} */ n) => "B".repeat(40) + String(n).padStart(4, "0").replace(/\d/g, (d) => "abcdefghij"[Number(d)]);
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "ia-fit-relay-"));
test("relais : premier dépôt, lecture après un numéro, clé d'accès exigée ensuite", async () => {
const s = await startServer();
try {
let r = await s.fetch(`/api/journals/${ID}/events`, { headers: auth(TOKEN) });
assert.equal(r.status, 404, "journal inconnu avant le premier dépôt");
r = await push(s, ID, TOKEN, [blob(1), blob(2)]);
assert.equal(r.status, 200);
assert.deepEqual(await r.json(), { last: 2, accepted: 2 });
r = await push(s, ID, TOKEN, [blob(3)]);
assert.deepEqual(await r.json(), { last: 3, accepted: 1 });
r = await s.fetch(`/api/journals/${ID}/events?after=1`, { headers: auth(TOKEN) });
assert.deepEqual(await r.json(), { events: [{ seq: 2, blob: blob(2) }, { seq: 3, blob: blob(3) }], last: 3, more: false });
r = await s.fetch(`/api/journals/${ID}/events?after=3`, { headers: auth(TOKEN) });
assert.deepEqual(await r.json(), { events: [], last: 3, more: false });
// Sans clé, avec une autre clé : refusé, en lecture comme en écriture.
assert.equal((await s.fetch(`/api/journals/${ID}/events`)).status, 401);
assert.equal((await s.fetch(`/api/journals/${ID}/events`, { headers: auth("autre-cle") })).status, 403);
assert.equal((await push(s, ID, "autre-cle", [blob(4)])).status, 403);
assert.equal((await s.fetch(`/api/journals/${ID}/events?after=-1`, { headers: auth(TOKEN) })).status, 400);
// Sur disque : un en-tête (empreinte, jamais la clé) puis une ligne par bloc.
const text = fs.readFileSync(path.join(s.dataDir, "journals", ID + ".jsonl"), "utf8");
const lines = text.trim().split("\n").map((l) => JSON.parse(l));
assert.equal(lines.length, 4);
assert.match(lines[0].auth, /^[0-9a-f]{64}$/);
assert.ok(!text.includes(TOKEN));
assert.deepEqual(lines[3], { seq: 3, blob: blob(3) });
} finally {
await s.close();
}
});
test("relais : quotas (bloc, nombre de blocs, taille du journal) et blocs mal formés", async () => {
const s = await startServer({ limits: { blobBytes: 100, blobsPerRequest: 3, journalBytes: 400 } });
try {
const bad = async (/** @type {unknown} */ body, /** @type {number} */ status, /** @type {string} */ error) => {
const r = await s.fetch(`/api/journals/${ID}/events`, { method: "POST", headers: auth(TOKEN), body: JSON.stringify(body) });
assert.equal(r.status, status, error);
assert.equal((await r.json()).error, error);
};
await bad(["x".repeat(101)], 413, "blob_too_large");
await bad([blob(1), blob(2), blob(3), blob(4)], 413, "too_many_blobs");
await bad([], 400, "invalid_request");
await bad(["pas du base64 !"], 400, "invalid_blob");
await bad({ blob: blob(1) }, 400, "invalid_request");
assert.equal((await push(s, ID, TOKEN, [blob(1), blob(2), blob(3)])).status, 200);
await bad([blob(4), blob(5), blob(6)], 413, "journal_full");
assert.equal((await s.fetch("/api/journals/court/events", { headers: auth(TOKEN) })).status, 404);
} finally {
await s.close();
}
});
test("relais : écritures concurrentes sérialisées, numéros continus", async () => {
const relay = createRelay(tmp());
await Promise.all(Array.from({ length: 20 }, (_, i) => relay.append(ID, TOKEN, [blob(i), blob(100 + i)])));
const { events, last } = await relay.read(ID, TOKEN, 0);
assert.equal(last, 40);
assert.deepEqual(events.map((e) => e.seq), Array.from({ length: 40 }, (_, i) => i + 1));
});
test("relais : lecture par pages, ligne incomplète réparée au chargement", async () => {
const dir = tmp();
const relay = createRelay(dir, { limits: { blobsPerRead: 2 } });
await relay.append(ID, TOKEN, [blob(1), blob(2), blob(3)]);
let page = await relay.read(ID, TOKEN, 0);
assert.deepEqual([page.events.map((e) => e.seq), page.more], [[1, 2], true]);
page = await relay.read(ID, TOKEN, 2);
assert.deepEqual([page.events.map((e) => e.seq), page.more], [[3], false]);
// Arrêt brutal au milieu d'une écriture : la ligne coupée est retirée.
fs.appendFileSync(path.join(dir, "journals", ID + ".jsonl"), '{"seq":4,"bl');
const reopened = createRelay(dir);
assert.equal((await reopened.read(ID, TOKEN, 0)).last, 3);
assert.deepEqual(await reopened.append(ID, TOKEN, [blob(4)]), { last: 4, accepted: 1 });
assert.equal((await createRelay(dir).read(ID, TOKEN, 3)).events[0].blob, blob(4));
});
test("relais : effacement des journaux inactifs depuis 400 jours, une lecture compte comme activité", async () => {
const dir = tmp();
let t = Date.parse("2026-01-01T00:00:00Z");
const relay = createRelay(dir, { now: () => t });
const other = "AAAAAAAAAAAAAAAAAAAAAA";
await relay.append(ID, TOKEN, [blob(1)]);
await relay.append(other, TOKEN, [blob(1)]);
const file = (/** @type {string} */ id) => path.join(dir, "journals", id + ".jsonl");
const old = new Date(t - 401 * 864e5);
fs.utimesSync(file(ID), old, old);
fs.utimesSync(file(other), old, old);
t += 2 * 864e5;
await relay.read(other, TOKEN, 0); // lu : redevient actif
assert.equal(await relay.purgeInactive(), 1);
assert.equal(fs.existsSync(file(ID)), false);
assert.equal(fs.existsSync(file(other)), true);
assert.equal(await relay.owns(ID, TOKEN), false);
});
test("adresse du client : X-Real-IP, sinon le DERNIER élément de X-Forwarded-For", () => {
const req = (/** @type {Record<string, string>} */ headers) => /** @type {any} */ ({ headers, socket: { remoteAddress: "10.0.0.1" } });
assert.equal(clientIp(req({ "x-real-ip": "203.0.113.7", "x-forwarded-for": "1.1.1.1, 203.0.113.7" })), "203.0.113.7");
assert.equal(clientIp(req({ "x-forwarded-for": "1.1.1.1, 2.2.2.2, 203.0.113.7" })), "203.0.113.7", "le début est inventé par le client");
assert.equal(clientIp(req({})), "10.0.0.1");
});
test("limite de requêtes : par adresse, en fenêtre, et non contournable par un faux X-Forwarded-For", async () => {
let t = 0;
const limiter = createRateLimiter({ max: 2, windowMs: 1000, now: () => t });
assert.equal(limiter.hit("a"), 0);
assert.equal(limiter.hit("a"), 0);
assert.equal(limiter.hit("a"), 1);
assert.equal(limiter.hit("b"), 0);
t = 1000;
assert.equal(limiter.hit("a"), 0);
const s = await startServer({ rate: { max: 3, windowMs: 60e3 } });
try {
const statuses = [];
for (let i = 0; i < 5; i++) {
// Le client change le début de X-Forwarded-For ; le proxy ajoute sa vraie adresse à la fin.
const r = await s.fetch("/.well-known/oauth-authorization-server", { headers: { "x-forwarded-for": `9.9.9.${i}, 203.0.113.7` } });
statuses.push(r.status);
}
assert.deepEqual(statuses, [200, 200, 200, 429, 429]);
// Le site statique n'est pas limité.
assert.equal((await s.fetch("/", { headers: { "x-forwarded-for": "203.0.113.7" } })).status, 200);
} finally {
await s.close();
}
});