$ cat docs/audit.md
OpenAPI and tupik auditOpenAPI e tupik audit
Every route carries metadata: who may call it (access), which fields are personal data (classify), which errors it raises (errors) and what its middleware guarantees (tags). @tupik/openapi turns it into documentation and a CI gate.Toda rota carrega metadados: quem pode chamar (access), quais campos são dado pessoal (classify), que erros levanta (errors) e o que o middleware garante (tags). O @tupik/openapi transforma isso em documentação e trava de CI.
OpenAPI from the metadataOpenAPI a partir dos metadados
import { generateOpenApiDocument } from '@tupik/openapi';
const document = generateOpenApiDocument(app, {
info: { title: 'Clinic API', version: '1.0.0' },
securitySchemes: { bearer: { type: 'http', scheme: 'bearer' } },
}); security:[]on public routes, the scheme when a principal is required,[{}, { bearer: [] }]forauth: 'optional'.x-accesswith the access kind:public,authenticated,policyorowner.x-data-classon every field classified withclassify, also in derived schemas (z.array(User),.pick(), nesting), since the class lives on the field schema.- One
application/problem+jsonresponse per status with thecodeenum: declared errors plusUNAUTHORIZED,FORBIDDENandNOT_FOUNDfrom the access rule.
security:[]em rota pública, o esquema quando exige principal,[{}, { bearer: [] }]comauth: 'optional'.x-accesscom o tipo de acesso:public,authenticated,policyouowner.x-data-classem todo campo classificado comclassify, inclusive em schemas derivados (z.array(User),.pick(), aninhamento), porque a classe fica no schema do campo.- Uma resposta
application/problem+jsonpor status com o enum decode: erros declarados maisUNAUTHORIZED,FORBIDDENeNOT_FOUNDda regra de acesso.
The auditA auditoria
The module must export the app as default or app. Pass it with a path (./dist/app.js), not a bare name.
O módulo precisa exportar o app como default ou app. Passe com caminho (./dist/app.js), não com nome solto.
npx tupik audit ./dist/app.js # text, fails on errors
npx tupik audit ./dist/app.js --format sarif --out audit.sarif --fail-on warning
npx tupik audit ./dist/app.js --baseline contract.jsonnpx tupik audit ./dist/app.js # texto, falha em erro
npx tupik audit ./dist/app.js --format sarif --out audit.sarif --fail-on warning
npx tupik audit ./dist/app.js --baseline contract.json | RuleRegra | SeverityGravidade | FindsAcha |
|---|---|---|
public-sensitive-data | error | A public route receives or returns pii or health.Rota pública que recebe ou devolve pii ou health. |
sensitive-data | warning | Any other route with pii or health: record purpose and legal basis.Outra rota com pii ou health: registre finalidade e base legal. |
write-without-rate-limit | warning | POST, PUT, PATCH or DELETE without a middleware tagged 'rate-limited'.POST, PUT, PATCH ou DELETE sem middleware marcado 'rate-limited'. |
id-without-owner | warning | A :id, :somethingId or :something_id route without owner nor a policy (BOLA risk).Rota com :id, :algoId ou :algo_id sem owner nem política (risco de BOLA). |
public-route | note | The route is public.A rota é pública. |
breaking-change | error | Contract change against --baseline that breaks clients.Mudança de contrato contra o --baseline que quebra clientes. |
contract-warning | warning | Contract change reviewers should notice: access, required fields, new sensitive output.Mudança de contrato que a revisão deve ver: acesso, campo obrigatório, nova saída sensível. |
rateLimit from @tupik/middleware tags itself 'rate-limited'. For your own limiter use withTags(middleware, 'rate-limited'), or change the tag with --rate-limit-tag. --disable rule,... turns rules off. --fail-on takes error (default), warning, note or none. Formats: text, json, sarif; the SARIF file uploads to GitHub code scanning.
O rateLimit do @tupik/middleware se marca como 'rate-limited'. Para um limitador seu, use withTags(middleware, 'rate-limited'), ou troque a marca com --rate-limit-tag. --disable regra,... desliga regras. --fail-on aceita error (padrão), warning, note ou none. Formatos: text, json, sarif; o SARIF sobe no code scanning do GitHub.
Some findings are right on purpose: a sign-up route is public and receives an e-mail. Accept that one finding on that route with acceptAudit(rule, reason) in tags, instead of turning the rule off for the whole app with --disable.
Alguns achados estão certos de propósito: a rota de cadastro é pública e recebe um e-mail. Aceite aquele achado naquela rota com acceptAudit(regra, motivo) em tags, em vez de desligar a regra no app inteiro com --disable.
import { classify, createModule } from '@tupik/core';
import { acceptAudit } from '@tupik/openapi';
import { z } from 'zod';
const SignUp = classify(z.object({ email: z.string(), password: z.string() }), { email: 'pii', password: 'secret' });
createModule('/auth').post('/sign-up', {
access: 'public',
schema: { body: SignUp },
// the reason is mandatory and shows up in every report
tags: [acceptAudit('public-sensitive-data', 'sign-up receives the e-mail before there is a user')],
handler: () => ({ ok: true }),
});import { classify, createModule } from '@tupik/core';
import { acceptAudit } from '@tupik/openapi';
import { z } from 'zod';
const SignUp = classify(z.object({ email: z.string(), password: z.string() }), { email: 'pii', password: 'secret' });
createModule('/auth').post('/sign-up', {
access: 'public',
schema: { body: SignUp },
// o motivo é obrigatório e aparece em todo relatório
tags: [acceptAudit('public-sensitive-data', 'sign-up receives the e-mail before there is a user')],
handler: () => ({ ok: true }),
}); - The finding stays in the report as a
notewithacceptedset to the reason, so it no longer fails--fail-on warningorerror. - The text report prints
accepted: <reason>; SARIF marks the result as suppressed in source with the reason as justification. - The reason is mandatory:
acceptAuditthrows on an empty one, and an acceptance tag without a reason is ignored, with a message in the finding saying so.
- O achado fica no relatório como
notecomacceptedigual ao motivo, então não falha mais com--fail-on warningouerror. - O relatório em texto imprime
accepted: <motivo>; o SARIF marca o resultado como suprimido no código, com o motivo como justificativa. - O motivo é obrigatório:
acceptAuditlança erro com motivo vazio, e uma marca de aceite sem motivo é ignorada, com uma mensagem no achado dizendo isso.
tupik contract snapshot|check (also the tupik-contract bin) records access, auth level, data classes and required body fields. "This route stopped requiring login" or "this route now returns the diagnosis" shows up in review.
O tupik contract snapshot|check (e o bin tupik-contract) grava acesso, nível de auth, classes de dado e campos obrigatórios do corpo. "Esta rota deixou de exigir login" ou "esta rota passou a devolver o diagnóstico" aparece na revisão.