SPB Git

Repository Public

acces-et-injections.test.ts 31.2 KB 585 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : UQO Éval — Le Grand Défi Immobilier8 * File             : tests/security/acces-et-injections.test.ts9 * Module           : tests10 * Repository       : https://git.spboucher.ai/uqo-eval-jeux11 * Project Website  : https://jeux.uqo-eval.app12 * Created          : 2026-11-2513 * Last Modified    : 2026-11-2514 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/** Cloisonnement des parties, injections (SQL, XSS), en-têtes de sécurité, CSRF et limites de débit. */44import { afterAll, beforeAll, describe, expect, it } from "vitest";45import { ADMIN_GET, Player, XRW, closeDatabase, makeCompetition, openServer, oracle, resetGameData, sql, type App } from "../helpers/api.ts";4647let app: App;48let competitionId = "";49let alice: Player;50let bob: Player;5152beforeAll(async () => {53  await resetGameData();54  app = await openServer();55  competitionId = (await makeCompetition({ name: "Cloisonnement", size: 4, seed: "cloisonnement" })).id;56  alice = await Player.start(app, { displayName: "Alice Cloison", competitionId });57  bob = await Player.start(app, { displayName: "Bob Cloison", competitionId });58});5960afterAll(async () => {61  await app.close();62  await closeDatabase();63});6465const GAME_ROUTES = ["/api/v1/game/current", "/api/v1/results/me", "/api/v1/results/me/analytics", "/api/v1/results/me/review"];6667describe("Accès à la partie d'un autre joueur", () => {68  it("le témoin d'un joueur avec l'identifiant de partie d'un autre → 401", async () => {69    for (const url of GAME_ROUTES) {70      const res = await app.inject({ method: "GET", url, headers: { "x-game": bob.sessionId, cookie: alice.cookie } });71      expect(res.statusCode, url).toBe(401);72      expect(res.json().error.code).toBe("no_session");73    }74  });7576  it("le jeton d'un joueur rejoué sous le nom du témoin d'un autre → 401", async () => {77    const aliceToken = alice.cookie.split("=")[1]!;78    const forged = `gdi_${bob.sessionId.slice(0, 8)}=${aliceToken}`;79    const res = await app.inject({ method: "GET", url: "/api/v1/game/current", headers: { "x-game": bob.sessionId, cookie: forged } });80    expect(res.statusCode).toBe(401);81    const both = await app.inject({ method: "GET", url: "/api/v1/game/current", headers: { "x-game": bob.sessionId, cookie: `${alice.cookie}; ${forged}` } });82    expect(both.statusCode).toBe(401);83  });8485  it("ne peut pas répondre à la place d'un autre joueur", async () => {86    const q = await bob.question();87    const truth = await oracle(q.id);88    const res = await app.inject({89      method: "POST", url: "/api/v1/game/answer", headers: { "x-game": bob.sessionId, cookie: alice.cookie },90      payload: { questionId: q.id, choiceId: truth.wrong[0]!.id, idempotencyKey: "sabotage-de-bob-1" },91    });92    expect(res.statusCode).toBe(401);93    const [row] = await sql<{ answered: number; n: number }[]>`94      select s.answered, (select count(*)::int from answers a where a.session_id = s.id) as n from game_sessions s where s.id = ${bob.sessionId}`;95    expect(row).toEqual({ answered: 0, n: 0 });96  });9798  it("refuse l'accès sans témoin, sans identifiant, ou avec un identifiant mal formé (401)", async () => {99    const cases: Record<string, string>[] = [100      {},101      { "x-game": alice.sessionId },102      { cookie: alice.cookie },103      { "x-game": "pas-un-uuid", cookie: alice.cookie },104      { "x-game": `${alice.sessionId}' or '1'='1`, cookie: alice.cookie },105      { "x-game": alice.sessionId, cookie: `gdi_${alice.sessionId.slice(0, 8)}=` },106      { "x-game": alice.sessionId, cookie: `gdi_${alice.sessionId.slice(0, 8)}=jeton-invente-de-toutes-pieces-0123456789abcdef` },107      { "x-game": "00000000-0000-4000-8000-000000000000", cookie: "gdi_00000000=n-importe-quoi" },108    ];109    for (const headers of cases) {110      for (const url of GAME_ROUTES) {111        const res = await app.inject({ method: "GET", url, headers });112        expect(res.statusCode, `${url} ${JSON.stringify(headers)}`).toBe(401);113      }114      const post = await app.inject({ method: "POST", url: "/api/v1/game/answer", headers, payload: { questionId: alice.sessionId, choiceId: alice.sessionId, idempotencyKey: "sans-partie-1" } });115      expect(post.statusCode).toBe(401);116    }117  });118119  it("chaque joueur ne voit que sa propre partie avec ses propres identifiants", async () => {120    const a = (await alice.current()).json();121    const b = (await bob.current()).json();122    expect(a.session).toMatchObject({ id: alice.sessionId, displayName: "Alice Cloison" });123    expect(b.session).toMatchObject({ id: bob.sessionId, displayName: "Bob Cloison" });124  });125126  it("connaître l'identifiant de partie d'un autre (visible au classement) ne suffit pas à lire ses résultats", async () => {127    await bob.playToEnd(() => ({ right: true }));128    const board = (await app.inject({ method: "GET", url: `/api/v1/leaderboard/${competitionId}` })).json();129    const bobId = board.rows.find((r: { displayName: string }) => r.displayName === "Bob Cloison").sessionId;130    expect(bobId).toBe(bob.sessionId);131    for (const url of GAME_ROUTES) {132      expect((await app.inject({ method: "GET", url, headers: { "x-game": bobId } })).statusCode).toBe(401);133      expect((await app.inject({ method: "GET", url, headers: { "x-game": bobId, cookie: alice.cookie } })).statusCode).toBe(401);134    }135    // l'en-tête x-game seul ne sert qu'à marquer « moi » au classement : aucune donnée supplémentaire136    const asBob = (await app.inject({ method: "GET", url: `/api/v1/leaderboard/${competitionId}`, headers: { "x-game": bobId } })).json();137    expect(Object.keys(asBob.me).sort()).toEqual(Object.keys(asBob.rows[0]).sort());138  });139140  it("résultats, rapport et révision refusés tant que la partie n'est pas terminée (409), accordés ensuite", async () => {141    for (const url of GAME_ROUTES.slice(1)) {142      expect((await alice.get(url)).statusCode, url).toBe(409);143      expect((await bob.get(url)).statusCode, url).toBe(200);144    }145    await alice.playToEnd(() => ({ right: false }), 3);146    for (const url of GAME_ROUTES.slice(1)) expect((await alice.get(url)).statusCode, `${url} à 3 sur 4`).toBe(409);147    await alice.playToEnd(() => ({ right: false }));148    for (const url of GAME_ROUTES.slice(1)) expect((await alice.get(url)).statusCode, `${url} terminée`).toBe(200);149  });150151  it("un témoin de joueur n'ouvre pas l'administration", async () => {152    const res = await app.inject({ method: "GET", url: "/api/v1/admin/participants", headers: alice.headers });153    expect(res.statusCode).toBe(401);154    const forged = await app.inject({ method: "GET", url: "/api/v1/admin/participants", headers: { cookie: `gdi_admin=${alice.cookie.split("=")[1]}` } });155    expect(forged.statusCode).toBe(401);156  });157});158159describe("Injection SQL", () => {160  const PAYLOADS = [161    "Robert'); DROP TABLE participants;--",162    "x' OR '1'='1",163    "a\"; delete from answers; --",164    "'; update game_sessions set correct = 100; --",165    "Bobby\\'; truncate competitions cascade; --",166    "$$; drop table questions; $$",167  ];168169  it("un nom contenant du SQL est enregistré tel quel, comme une simple chaîne", async () => {170    for (const displayName of PAYLOADS) {171      const player = new Player(app);172      const res = await player.rawStart({ displayName, competitionId });173      expect(res.statusCode, displayName).toBe(200);174      const [row] = await sql<{ display_name: string }[]>`175        select p.display_name from participants p join game_sessions s on s.participant_id = p.id where s.id = ${player.sessionId}`;176      expect(row!.display_name).toBe(displayName.replace(/\s+/g, " ").trim().slice(0, 40));177    }178  });179180  it("aucune table n'a été vidée, supprimée ou modifiée par ces noms", async () => {181    const [row] = await sql<{ participants: number; questions: number; competitions: number; cheats: number; bob: number }[]>`182      select (select count(*)::int from participants) as participants, (select count(*)::int from questions where competition_id = ${competitionId}) as questions,183             (select count(*)::int from competitions) as competitions, (select count(*)::int from game_sessions where correct = 100) as cheats,184             (select count(*)::int from answers where session_id = ${bob.sessionId}) as bob`;185    expect(row).toEqual({ participants: 2 + PAYLOADS.length, questions: 4, competitions: 1, cheats: 0, bob: 4 });186  });187188  it("la recherche du classement traite le texte comme du texte (aucune injection, aucun joker)", async () => {189    const board = async (q: string) => app.inject({ method: "GET", url: `/api/v1/leaderboard/${competitionId}?q=${encodeURIComponent(q)}` });190    const baseline = (await board("")).json();191    expect(baseline.totalFinished).toBe(2);192    for (const q of ["' OR 1=1 --", "'; drop table participants; --", "%", "_", "\\", "' union select token_hash from s --", "*", ".*"]) {193      const res = await board(q);194      expect(res.statusCode, q).toBe(200);195      expect(res.json().matches, q).toBe(0);196      expect(res.json().rows).toEqual([]);197      expect(res.json().totalFinished).toBe(2);198      expect(res.body).not.toMatch(/token_hash|[0-9a-f]{64}/);199    }200    const real = (await board("bob")).json();201    expect(real.matches).toBe(1);202    const tooLong = await board("' union select token_hash from game_sessions --");203    expect(tooLong.statusCode).toBe(400); // plus de 40 caractères : refusé avant toute recherche204    const [row] = await sql<{ n: number }[]>`select count(*)::int as n from participants`;205    expect(row!.n).toBe(2 + PAYLOADS.length);206  });207208  it("les paramètres d'URL et de corps mal formés donnent 400 ou 404, jamais 500", async () => {209    const attempts = [210      await app.inject({ method: "GET", url: `/api/v1/leaderboard/${encodeURIComponent("' or 1=1 --")}` }),211      await app.inject({ method: "GET", url: `/api/v1/leaderboard/${competitionId}?page=${encodeURIComponent("1; drop table x")}` }),212      await app.inject({ method: "GET", url: `/api/v1/leaderboard/${competitionId}?cours=${encodeURIComponent("IMM1003' or '1'='1")}` }),213      await app.inject({ method: "GET", url: `/api/v1/competitions/${encodeURIComponent("' or 1=1 --")}` }),214      await app.inject({ method: "POST", url: "/api/v1/sessions/resume", headers: XRW, payload: { resumeCode: "' or '1'='1' --" } }),215      await app.inject({ method: "POST", url: "/api/v1/sessions", headers: XRW, payload: { displayName: "Injection Id", course: null, mode: "official", consent: true, competitionId: "' or 1=1 --" } }),216      await app.inject({ method: "GET", url: `/api/v1/admin/participants?competitionId=${encodeURIComponent("' or 1=1 --")}`, headers: ADMIN_GET }),217      await app.inject({ method: "GET", url: `/api/v1/admin/sessions/${encodeURIComponent("' or 1=1 --")}`, headers: ADMIN_GET }),218    ];219    for (const res of attempts) {220      expect([400, 404]).toContain(res.statusCode);221      expect(res.body).not.toMatch(/syntax error|postgres|relation|select |stack|at \w+ \(/i);222    }223  });224225  it("la recherche de l'administration échappe les jokers et les apostrophes", async () => {226    for (const q of ["%", "_", "' or 1=1 --", "\\"]) {227      const res = await app.inject({ method: "GET", url: `/api/v1/admin/participants?q=${encodeURIComponent(q)}`, headers: ADMIN_GET });228      expect(res.statusCode, q).toBe(200);229      const names = (res.json().rows as { display_name: string }[]).map((r) => r.display_name);230      expect(names.every((name) => name.toLowerCase().includes(q.toLowerCase())), q).toBe(true);231    }232  });233});234235describe("XSS dans le nom", () => {236  const cases: [string, string][] = [237    ["<script>alert(1)</script>", "scriptalert(1)/script"],238    ["<img src=x onerror=alert(document.cookie)>", "img src=x onerror=alert(document.cookie)"],239    ["Zoé <b>Grasse</b>", "Zoé bGrasse/b"],240    ["<<svg/onload=alert(1)>>", "svg/onload=alert(1)"],241    ["Tab\tulation\u0000 Nulle\u001b[31m", "Tabulation Nulle[31m"],242  ];243244  it.each(cases)("le nom %j est stocké nettoyé : %j (ni chevron ni caractère de contrôle)", async (input, stored) => {245    const player = new Player(app);246    const res = await player.rawStart({ displayName: input, competitionId });247    expect(res.statusCode).toBe(200);248    expect(res.headers["content-type"]).toMatch(/^application\/json/);249    expect(res.json().session.displayName).toBe(stored);250    const [row] = await sql<{ display_name: string }[]>`251      select p.display_name from participants p join game_sessions s on s.participant_id = p.id where s.id = ${player.sessionId}`;252    expect(row!.display_name).toBe(stored);253    // eslint-disable-next-line no-control-regex254    expect(row!.display_name).not.toMatch(/[<>\u0000-\u001f\u007f]/);255  });256257  it("le classement renvoie ces noms en JSON (jamais en HTML), sans chevron", async () => {258    const res = await app.inject({ method: "GET", url: `/api/v1/leaderboard/${competitionId}` });259    expect(res.headers["content-type"]).toMatch(/^application\/json/);260    expect(res.headers["x-content-type-options"]).toBe("nosniff");261    expect(res.body).not.toMatch(/<script|<img|<svg|<b>/i);262    const names = (res.json().inProgress as { displayName: string }[]).map((r) => r.displayName);263    expect(names).toContain("scriptalert(1)/script");264    expect(names.every((name) => !/[<>]/.test(name))).toBe(true);265  });266267  it("refuse un nom fait uniquement de balises ou de ponctuation (400)", async () => {268    for (const displayName of ["<>", "<<>>", "< >", "<!---->"]) {269      const res = await app.inject({ method: "POST", url: "/api/v1/sessions", headers: XRW, payload: { displayName, course: null, mode: "official", consent: true, competitionId } });270      expect(res.statusCode, displayName).toBe(400);271    }272  });273274  it("un motif de signalement contenant du HTML est renvoyé à l'administration en JSON", async () => {275    const q = bob.played[0]!.questionId;276    const res = await app.inject({ method: "POST", url: "/api/v1/game/flag", headers: bob.headers, payload: { questionId: q, reason: "<script>alert('x')</script> photo erronée" } });277    expect(res.statusCode).toBe(200);278    const flags = await app.inject({ method: "GET", url: "/api/v1/admin/flags", headers: ADMIN_GET });279    expect(flags.headers["content-type"]).toMatch(/^application\/json/);280    expect(flags.headers["x-content-type-options"]).toBe("nosniff");281  });282});283284describe("En-têtes de sécurité", () => {285  const routes: [string, string, Record<string, string>][] = [286    ["GET", "/api/v1/health", {}],287    ["GET", "/api/v1/home", {}],288    ["GET", "/api/v1/game/current", {}], // 401289    ["GET", "/api/v1/route-inexistante", {}], // 404290    ["POST", "/api/v1/sessions", {}], // 403291    ["GET", "/api/v1/admin/dashboard", {}], // 401292  ];293294  it.each(routes)("%s %s porte CSP, nosniff, anti-cadre, politique de référent et no-store", async (method, url, headers) => {295    const res = await app.inject({ method: method as "GET", url, headers, payload: method === "POST" ? {} : undefined });296    expect(res.headers["x-content-type-options"]).toBe("nosniff");297    expect(res.headers["x-frame-options"]).toBe("DENY");298    expect(res.headers["referrer-policy"]).toBe("same-origin");299    expect(res.headers["cache-control"]).toBe("no-store");300    expect(res.headers["permissions-policy"]).toMatch(/geolocation=\(\)/);301    const csp = String(res.headers["content-security-policy"]);302    expect(csp).toMatch(/default-src 'self'/);303    expect(csp).toMatch(/frame-ancestors 'none'/);304    expect(csp).toMatch(/base-uri 'self'/);305    expect(csp).toMatch(/form-action 'self'/);306    const scriptSrc = csp.split(";").map((d) => d.trim()).find((d) => d.startsWith("script-src"))!;307    expect(scriptSrc).toBe("script-src 'self'");308    expect(csp).not.toMatch(/unsafe-eval/);309    expect(csp).not.toMatch(/\*/);310  });311312  it("le témoin de partie est HttpOnly, SameSite=Lax, limité à la racine, et son nom ne révèle que 8 caractères de l'identifiant", async () => {313    const player = new Player(app);314    const res = await player.rawStart({ displayName: "Témoin Vérifié", competitionId });315    const header = String(res.headers["set-cookie"]);316    expect(header).toMatch(/HttpOnly/i);317    expect(header).toMatch(/SameSite=Lax/i);318    expect(header).toMatch(/Path=\//);319    expect(header).toMatch(/Max-Age=\d+/);320    expect(res.cookies).toHaveLength(1);321    expect(res.cookies[0]!.name).toBe(`gdi_${player.sessionId.slice(0, 8)}`);322  });323324  it("les erreurs ne divulguent ni pile d'exécution ni détail interne", async () => {325    const res = await app.inject({ method: "POST", url: "/api/v1/sessions", headers: { ...XRW, "content-type": "application/json" }, payload: "{pas du json" });326    expect(res.statusCode).toBe(400);327    expect(Object.keys(res.json())).toEqual(["error"]);328    expect(Object.keys(res.json().error).sort()).toEqual(["code", "message"]);329    expect(res.body).not.toMatch(/SyntaxError|Unexpected token|node_modules|\.ts:\d+/);330    const big = await app.inject({ method: "POST", url: "/api/v1/sessions", headers: XRW, payload: { displayName: "x".repeat(70_000), mode: "official", consent: true } });331    expect(big.statusCode).toBe(413);332  });333});334335describe("CSRF", () => {336  it("POST /sessions sans x-requested-with → 403, aucune partie créée, aucun témoin posé", async () => {337    const [before] = await sql<{ n: number }[]>`select count(*)::int as n from game_sessions`;338    const payload = { displayName: "Victime CSRF", course: null, mode: "official", competitionId, consent: true };339    const none = await app.inject({ method: "POST", url: "/api/v1/sessions", payload });340    expect(none.statusCode).toBe(403);341    expect(none.json().error.code).toBe("csrf");342    expect(none.cookies).toEqual([]);343    for (const value of ["XMLHttpRequest", "GDI", "gdi ", ""]) {344      const res = await app.inject({ method: "POST", url: "/api/v1/sessions", headers: { "x-requested-with": value }, payload });345      expect(res.statusCode, JSON.stringify(value)).toBe(403);346    }347    // un formulaire HTML d'un site tiers (seul type de corps possible sans préflight CORS)348    const form = await app.inject({ method: "POST", url: "/api/v1/sessions", headers: { "content-type": "application/x-www-form-urlencoded", origin: "https://site-malveillant.test" }, payload: "displayName=Victime&mode=daily&consent=true" });349    expect([403, 415]).toContain(form.statusCode);350    const [after] = await sql<{ n: number }[]>`select count(*)::int as n from game_sessions`;351    expect(after!.n).toBe(before!.n);352  });353354  it("POST /sessions/resume sans x-requested-with → 403", async () => {355    const res = await app.inject({ method: "POST", url: "/api/v1/sessions/resume", payload: { resumeCode: alice.resumeCode } });356    expect(res.statusCode).toBe(403);357    expect(res.cookies).toEqual([]);358  });359360  it("les routes de jeu exigent l'en-tête x-game, qu'un site tiers ne peut pas envoyer : le témoin seul ne suffit pas", async () => {361    const carol = await Player.start(app, { displayName: "Carole CSRF", competitionId });362    const q = await carol.question();363    const res = await app.inject({ method: "POST", url: "/api/v1/game/answer", headers: { cookie: carol.cookie, origin: "https://site-malveillant.test" }, payload: { questionId: q.id, choiceId: q.choices[0]!.id, idempotencyKey: "csrf-carole-1" } });364    expect(res.statusCode).toBe(401);365    const [row] = await sql<{ answered: number }[]>`select answered from game_sessions where id = ${carol.sessionId}`;366    expect(row!.answered).toBe(0);367  });368369  it("n'émet aucun en-tête CORS permissif", async () => {370    const res = await app.inject({ method: "GET", url: "/api/v1/home", headers: { origin: "https://site-malveillant.test" } });371    expect(res.headers["access-control-allow-origin"]).toBeUndefined();372    expect(res.headers["access-control-allow-credentials"]).toBeUndefined();373    const preflight = await app.inject({ method: "OPTIONS", url: "/api/v1/sessions", headers: { origin: "https://site-malveillant.test", "access-control-request-method": "POST", "access-control-request-headers": "x-requested-with" } });374    expect(preflight.headers["access-control-allow-origin"]).toBeUndefined();375  });376});377378describe("Limites de débit", () => {379  const saved = { ...process.env };380  afterAll(() => {381    for (const key of ["RATE_LIMIT_MAX", "RATE_LIMIT_SESSIONS", "RATE_LIMIT_ANSWERS", "RATE_LIMIT_RESUME", "TRUSTED_PROXIES"]) {382      if (saved[key] === undefined) delete process.env[key];383      else process.env[key] = saved[key];384    }385  });386387  it("limite la création de parties par adresse (RATE_LIMIT_SESSIONS) : 429 rate_limited au-delà, rien de créé", async () => {388    process.env.RATE_LIMIT_SESSIONS = "3";389    const limited = await openServer();390    process.env.RATE_LIMIT_SESSIONS = saved.RATE_LIMIT_SESSIONS;391    try {392      const [before] = await sql<{ n: number }[]>`select count(*)::int as n from game_sessions`;393      const codes: number[] = [];394      for (let i = 0; i < 6; i++) {395        const res = await limited.inject({ method: "POST", url: "/api/v1/sessions", headers: XRW, payload: { displayName: `Débit ${i}`, course: null, mode: "official", competitionId, consent: true } });396        codes.push(res.statusCode);397        if (res.statusCode === 429) {398          expect(res.json().error.code).toBe("rate_limited");399          expect(res.headers["retry-after"]).toBeDefined();400          expect(res.cookies).toEqual([]);401        }402      }403      expect(codes).toEqual([200, 200, 200, 429, 429, 429]);404      const [after] = await sql<{ n: number }[]>`select count(*)::int as n from game_sessions`;405      expect(after!.n - before!.n).toBe(3);406      // la limite est par adresse : une autre adresse n'est pas touchée407      const other = await limited.inject({ method: "POST", url: "/api/v1/sessions", headers: XRW, remoteAddress: "203.0.113.7", payload: { displayName: "Autre Adresse", course: null, mode: "official", competitionId, consent: true } });408      expect(other.statusCode).toBe(200);409    } finally {410      await limited.close();411    }412  });413414  const forged = async (limited: App, remoteAddress: string | undefined, count: number, tag: string): Promise<number[]> => {415    const codes: number[] = [];416    for (let i = 0; i < count; i++) {417      const res = await limited.inject({418        method: "POST", url: "/api/v1/sessions", headers: { ...XRW, "x-forwarded-for": `198.51.100.${i + 1}` }, ...(remoteAddress ? { remoteAddress } : {}),419        payload: { displayName: `Adresse Fabriquée ${tag} ${i}`, course: null, mode: "official", competitionId, consent: true },420      });421      codes.push(res.statusCode);422    }423    return codes;424  };425426  it("un X-Forwarded-For fabriqué par un client extérieur est ignoré : la limite par adresse tient (429)", async () => {427    process.env.RATE_LIMIT_SESSIONS = "3";428    const limited = await openServer();429    process.env.RATE_LIMIT_SESSIONS = saved.RATE_LIMIT_SESSIONS;430    try {431      // connexion directe depuis une adresse publique, hors de la liste des mandataires de confiance432      expect(await forged(limited, "203.0.113.50", 8, "ext")).toEqual([200, 200, 200, 429, 429, 429, 429, 429]);433      // idem depuis le réseau local hors passerelle (192.168.x.x n'est pas de confiance)434      expect(await forged(limited, "192.168.2.77", 5, "lan")).toEqual([200, 200, 200, 429, 429]);435    } finally {436      await limited.close();437    }438  });439440  it("seuls les mandataires de confiance (boucle locale, 10.67.0.0/16) déclarent l'adresse du client", async () => {441    process.env.RATE_LIMIT_SESSIONS = "3";442    const limited = await openServer();443    process.env.RATE_LIMIT_SESSIONS = saved.RATE_LIMIT_SESSIONS;444    try {445      // la passerelle (10.67.0.1) relaie huit clients différents : chacun a son propre compteur446      expect(await forged(limited, "10.67.0.1", 8, "wg")).toEqual([200, 200, 200, 200, 200, 200, 200, 200]);447      // observation avec app.inject : l'adresse par défaut est 127.0.0.1, donc de confiance — l'en-tête y est honoré448      expect(await forged(limited, undefined, 8, "loc")).toEqual([200, 200, 200, 200, 200, 200, 200, 200]);449    } finally {450      await limited.close();451    }452  });453454  it("TRUSTED_PROXIES vide de confiance toute adresse : même la boucle locale ne peut plus déclarer le client", async () => {455    process.env.RATE_LIMIT_SESSIONS = "3";456    process.env.TRUSTED_PROXIES = "192.0.2.1";457    const limited = await openServer();458    process.env.RATE_LIMIT_SESSIONS = saved.RATE_LIMIT_SESSIONS;459    delete process.env.TRUSTED_PROXIES;460    try {461      expect(await forged(limited, undefined, 5, "strict")).toEqual([200, 200, 200, 429, 429]);462    } finally {463      await limited.close();464    }465  });466467  it("limite les réponses par minute (RATE_LIMIT_ANSWERS)", async () => {468    process.env.RATE_LIMIT_ANSWERS = "2";469    const limited = await openServer();470    process.env.RATE_LIMIT_ANSWERS = saved.RATE_LIMIT_ANSWERS;471    try {472      const player = await Player.start(limited, { displayName: "Mitraillette", competitionId });473      const codes: number[] = [];474      // l'ouverture (/game/next) et la réponse ont chacune leur compteur par partie : 2 ouvertures, 2 réponses, puis 429475      const q1 = (await player.next()).json().question;476      codes.push((await player.answer(q1.id, q1.choices[0].id)).statusCode);477      const q2 = (await player.next()).json().question;478      codes.push((await player.answer(q2.id, q2.choices[0].id)).statusCode);479      codes.push((await player.next()).statusCode);480      codes.push((await player.answer(q2.id, q2.choices[0].id)).statusCode);481      expect(codes).toEqual([200, 200, 429, 429]);482      const [row] = await sql<{ answered: number }[]>`select answered from game_sessions where id = ${player.sessionId}`;483      expect(row!.answered).toBe(2);484    } finally {485      await limited.close();486    }487  });488489  it("la limite de réponses est comptée PAR PARTIE : deux joueurs derrière la même adresse ne se gênent pas", async () => {490    process.env.RATE_LIMIT_ANSWERS = "2";491    const limited = await openServer();492    process.env.RATE_LIMIT_ANSWERS = saved.RATE_LIMIT_ANSWERS;493    try {494      const first = await Player.start(limited, { displayName: "Voisine de classe A", competitionId });495      const second = await Player.start(limited, { displayName: "Voisine de classe B", competitionId });496      const shoot = async (player: Player): Promise<number> => {497        const opened = await player.next();498        if (opened.statusCode !== 200) return opened.statusCode;499        const q = opened.json().question;500        return (await player.answer(q.id, q.choices[0].id)).statusCode;501      };502      // A épuise son quota…503      expect([await shoot(first), await shoot(first), await shoot(first)]).toEqual([200, 200, 429]);504      // … B, à la même adresse, garde le sien505      expect([await shoot(second), await shoot(second), await shoot(second)]).toEqual([200, 200, 429]);506      const rows = await sql<{ answered: number }[]>`select answered from game_sessions where id in ${sql([first.sessionId, second.sessionId])}`;507      expect(rows.map((r) => r.answered)).toEqual([2, 2]);508    } finally {509      await limited.close();510    }511  });512513  it("changer l'en-tête x-game ne donne pas de réponses supplémentaires à une partie (la clé de limite n'ouvre aucun accès)", async () => {514    process.env.RATE_LIMIT_ANSWERS = "2";515    const limited = await openServer();516    process.env.RATE_LIMIT_ANSWERS = saved.RATE_LIMIT_ANSWERS;517    try {518      const player = await Player.start(limited, { displayName: "Contourneuse", competitionId });519      const q = (await player.next()).json().question;520      // 30 requêtes avec des x-game fantaisistes : aucune n'est authentifiée, aucune réponse enregistrée521      const codes: number[] = [];522      for (let i = 0; i < 30; i++) {523        const fake = `00000000-0000-4000-8000-${String(i).padStart(12, "0")}`;524        codes.push((await limited.inject({ method: "POST", url: "/api/v1/game/answer", headers: { "x-game": fake, cookie: player.cookie }, payload: { questionId: q.id, choiceId: q.choices[0].id, idempotencyKey: `faux-jeu-${i}` } })).statusCode);525      }526      expect(new Set(codes)).toEqual(new Set([401]));527      const [row] = await sql<{ answered: number }[]>`select answered from game_sessions where id = ${player.sessionId}`;528      expect(row!.answered).toBe(0);529    } finally {530      await limited.close();531    }532  });533534  it("limite globale par adresse (RATE_LIMIT_MAX)", async () => {535    process.env.RATE_LIMIT_MAX = "5";536    const limited = await openServer();537    process.env.RATE_LIMIT_MAX = saved.RATE_LIMIT_MAX;538    try {539      const codes: number[] = [];540      for (let i = 0; i < 8; i++) codes.push((await limited.inject({ method: "GET", url: "/api/v1/health" })).statusCode);541      expect(codes).toEqual([200, 200, 200, 200, 200, 429, 429, 429]);542    } finally {543      await limited.close();544    }545  });546547  it("freine la recherche exhaustive des codes de reprise (RATE_LIMIT_RESUME, 60 par 10 minutes par défaut)", async () => {548    process.env.RATE_LIMIT_RESUME = "5";549    const limited = await openServer();550    delete process.env.RATE_LIMIT_RESUME;551    try {552      const codes: number[] = [];553      for (let i = 0; i < 8; i++) {554        const guess = `AAAA-BBBB-${String(i).padStart(4, "2")}`;555        codes.push((await limited.inject({ method: "POST", url: "/api/v1/sessions/resume", headers: XRW, payload: { resumeCode: guess } })).statusCode);556      }557      expect(codes).toEqual([404, 404, 404, 404, 404, 429, 429, 429]);558    } finally {559      await limited.close();560    }561    // valeur par défaut : 60 essais, le 61e est refusé562    const byDefault = await openServer();563    try {564      const codes: number[] = [];565      for (let i = 0; i < 62; i++) codes.push((await byDefault.inject({ method: "POST", url: "/api/v1/sessions/resume", headers: XRW, payload: { resumeCode: `CCCC-DDDD-${String(i).padStart(4, "3")}` } })).statusCode);566      expect(codes.slice(0, 60).every((c) => c === 404)).toBe(true);567      expect(codes.slice(60)).toEqual([429, 429]);568    } finally {569      await byDefault.close();570    }571  });572573  it("freine la recherche de la clé d'administration : 429 après 10 essais en 5 minutes", async () => {574    const limited = await openServer();575    try {576      const codes: number[] = [];577      for (let i = 0; i < 12; i++) codes.push((await limited.inject({ method: "POST", url: "/api/v1/admin/login", payload: { key: `essai-${i}` } })).statusCode);578      expect(codes.slice(0, 10)).toEqual(Array.from({ length: 10 }, () => 401));579      expect(codes.slice(10)).toEqual([429, 429]);580    } finally {581      await limited.close();582    }583  });584});585
Files main
Menu

Theme