Documentation menuMenu da documentação

$ 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

openapi.ts
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: [] }] for auth: 'optional'.
  • x-access with the access kind: public, authenticated, policy or owner.
  • x-data-class on every field classified with classify, also in derived schemas (z.array(User), .pick(), nesting), since the class lives on the field schema.
  • One application/problem+json response per status with the code enum: declared errors plus UNAUTHORIZED, FORBIDDEN and NOT_FOUND from the access rule.
  • security: [] em rota pública, o esquema quando exige principal, [{}, { bearer: [] }] com auth: 'optional'.
  • x-access com o tipo de acesso: public, authenticated, policy ou owner.
  • x-data-class em todo campo classificado com classify, inclusive em schemas derivados (z.array(User), .pick(), aninhamento), porque a classe fica no schema do campo.
  • Uma resposta application/problem+json por status com o enum de code: erros declarados mais UNAUTHORIZED, FORBIDDEN e NOT_FOUND da 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.

terminal
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.json
npx 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
RuleRegraSeverityGravidadeFindsAcha
public-sensitive-dataerrorA public route receives or returns pii or health.Rota pública que recebe ou devolve pii ou health.
sensitive-datawarningAny 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-limitwarningPOST, PUT, PATCH or DELETE without a middleware tagged 'rate-limited'.POST, PUT, PATCH ou DELETE sem middleware marcado 'rate-limited'.
id-without-ownerwarningA :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-routenoteThe route is public.A rota é pública.
breaking-changeerrorContract change against --baseline that breaks clients.Mudança de contrato contra o --baseline que quebra clientes.
contract-warningwarningContract 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.

auth.ts
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 note with accepted set to the reason, so it no longer fails --fail-on warning or error.
  • The text report prints accepted: <reason>; SARIF marks the result as suppressed in source with the reason as justification.
  • The reason is mandatory: acceptAudit throws 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 note com accepted igual ao motivo, então não falha mais com --fail-on warning ou error.
  • 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: acceptAudit lanç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.