$ cat docs/security-testing.md
Authorization tests and fuzzingTestes de autorização e fuzz
The access rules become tests, and hostile input proves nothing leaks. Both run in process through app.fetch, with no server.As regras de acesso viram teste, e entrada hostil prova que nada vaza. Os dois rodam no processo via app.fetch, sem servidor.
Generated access testsTestes de acesso gerados
import { fuzz, generateAccessTests } from '@tupik/testing';
const principals = {
owner: { headers: { authorization: 'Bearer ana' } },
other: { headers: { authorization: 'Bearer bia' } },
// optional: what a request without a principal still carries (an anonymous CSRF pair)
anonymous: { headers: { 'x-csrf-token': anonCsrf }, cookies: { '__Host-tupik_csrf': anonCsrf } },
};
const fixtures = {
'GET /notes/:id': { params: { id: 'note-of-ana' } }, // a record owned by principals.owner
'POST /notes': { body: { title: 'x' } },
};
for (const c of generateAccessTests(app, { principals, fixtures })) (c.skip ? it.skip : it)(c.name, c.run);
it('survives hostile input', async () => {
const report = await fuzz(app, { principals, fixtures, foreignIds: ['note-of-bia'], seed: 1 });
expect(report.failures).toEqual([]);
});import { fuzz, generateAccessTests } from '@tupik/testing';
const principals = {
owner: { headers: { authorization: 'Bearer ana' } },
other: { headers: { authorization: 'Bearer bia' } },
// opcional: o que um pedido sem principal ainda leva (um par CSRF anônimo)
anonymous: { headers: { 'x-csrf-token': anonCsrf }, cookies: { '__Host-tupik_csrf': anonCsrf } },
};
const fixtures = {
'GET /notes/:id': { params: { id: 'note-of-ana' } }, // um registro do principals.owner
'POST /notes': { body: { title: 'x' } },
};
for (const c of generateAccessTests(app, { principals, fixtures })) (c.skip ? it.skip : it)(c.name, c.run);
it('survives hostile input', async () => {
const report = await fuzz(app, { principals, fixtures, foreignIds: ['note-of-bia'], seed: 1 });
expect(report.failures).toEqual([]);
}); generateAccessTests creates "rejects an anonymous request (401)" for every route that needs a principal. For owner routes it adds "serves the owner" and "hides the owner's record from another principal" (403 or 404). A fixture names a valid request and, for routes with params, a record owned by principals.owner. A case without its fixture comes back with skip saying which one is missing.
O generateAccessTests cria "rejeita pedido anônimo (401)" para toda rota que exige principal. Nas rotas com owner, acrescenta "atende o dono" e "esconde o registro do dono de outro principal" (403 ou 404). Uma fixture descreve um pedido válido e, nas rotas com params, um registro do principals.owner. O caso sem fixture volta com skip dizendo qual falta.
principals.anonymous is optional. Without it the anonymous case sends nothing, so an app with csrf answers 403 on writes before access gives its 401, and the test fails. Give it what a visitor without a session still carries (an anonymous CSRF cookie and header): generateAccessTests, fuzz and tupik-fuzz --principals ({ owner, other, anonymous? } in the JSON file) send it and still expect the 401. A principal's values win over a fixture's.
O principals.anonymous é opcional. Sem ele o caso anônimo não envia nada, então um app com csrf responde 403 nas escritas antes de o access dar o 401, e o teste falha. Passe o que um visitante sem sessão ainda leva (cookie e header CSRF anônimos): generateAccessTests, fuzz e tupik-fuzz --principals ({ owner, other, anonymous? } no arquivo JSON) enviam isso e continuam esperando o 401. Os valores do principal vencem os da fixture.
expectProblem(response, { status?, type? }) takes a Response or the InjectResponse of createTestApp, so a problem from t.post(...) is checked without wrapping it.
O expectProblem(resposta, { status?, type? }) aceita uma Response ou a InjectResponse do createTestApp, então um problem de t.post(...) é conferido sem embrulhar.
FuzzingFuzz
npx tupik fuzz ./dist/app.js --principals principals.json --fixtures fixtures.json --seed 1
# same as tupik-fuzz from @tupik/testingnpx tupik fuzz ./dist/app.js --principals principals.json --fixtures fixtures.json --seed 1
# o mesmo que tupik-fuzz do @tupik/testing Inputs come from the JSON Schema of each route, with generic inputs when there is none. Body shape and prototype pollution attacks always run; the rest is sampled from the seed (runs, default 30 per route). Same seed, same inputs.
As entradas vêm do JSON Schema de cada rota, com entradas genéricas quando não há. Ataques de formato do corpo e de poluição de protótipo sempre rodam; o resto é sorteado pela seed (runs, padrão 30 por rota). Mesma seed, mesmas entradas.
- Wrong types, huge strings, extreme numbers, giant arrays, deep nesting.
__proto__andconstructor.prototypepayloads in the body and the query.- Extra fields such as
isAdmin,roleandownerId. - Hostile unicode: NUL, lone surrogates, right-to-left override, zero-width characters.
- Path traversal ids and ids of other principals (
foreignIds).
- Tipos errados, strings enormes, números extremos, arrays gigantes, aninhamento profundo.
- Payloads
__proto__econstructor.prototypeno corpo e na query. - Campos a mais como
isAdmin,roleeownerId. - Unicode hostil: NUL, surrogate solto, inversão direita-esquerda, caracteres de largura zero.
- Ids com path traversal e ids de outro principal (
foreignIds).
A case fails on a 5xx, a thrown error, a secret field in any response, a health field sent to anyone but the owner, a success on someone else's record, or a value planted on Object.prototype. The fuzzer never throws for a finding: read report.failures.
Um caso falha com 5xx, erro lançado, campo secret em qualquer resposta, campo health para quem não é o dono, sucesso no registro de outro, ou valor plantado em Object.prototype. O fuzz nunca lança erro por achado: leia report.failures.