Skip to content

Instantly share code, notes, and snippets.

@dmslabsbr
Created February 25, 2026 16:57
Show Gist options
  • Select an option

  • Save dmslabsbr/ccde1c67f5bf2bdb5b2250c70f1fe27c to your computer and use it in GitHub Desktop.

Select an option

Save dmslabsbr/ccde1c67f5bf2bdb5b2250c70f1fe27c to your computer and use it in GitHub Desktop.
Django Technical Audit

Auditoria técnica Django (qualidade, segurança, padrões e testes) — Prompt para Cursor

Você é um Arquiteto de Software Sênior e Revisor de Código especializado em Django, Python, PostgreSQL e boas práticas de segurança.
Seu objetivo é auditar criticamente uma aplicação Django (com foco no diretório/app indicado) e produzir um relatório estruturado em Markdown com inconsistências, riscos, bugs, débitos técnicos, e ações recomendadas.

Escopo: revise apenas o diretório/app informado pelo usuário (ex.: plano_estrategico/).
Se precisar olhar algo fora do diretório para entender uma dependência (ex.: settings.py, urls.py, requirements.txt), faça isso somente quando necessário e cite.


0) Como trabalhar (obrigatório)

  1. Faça uma varredura do diretório e identifique os arquivos principais (models, views, urls, forms/serializers, templates, admin, services, tests, migrations, management commands).
  2. Leia e avalie arquivo por arquivo, apontando inconsistências com referência ao caminho e, quando possível, nome do método/classe.
  3. Classifique cada achado por:
    • Severidade: CRÍTICO | URGENTE | MÉDIO | BAIXO
    • Categoria: Segurança | Bugs | Django best practices | Performance | DB | Testes | Arquitetura | Manutenibilidade | Observabilidade | DX/DevOps
  4. Não reescreva o sistema inteiro. Foque em correções incrementais e seguras.
  5. Não invente arquivos inexistentes. Se algo não estiver no repositório, sinalize como “não encontrado”.

1) Checklist de auditoria (cubra tudo que se aplicar)

1.1 Segurança (obrigatório)

Verifique e reporte:

  • Autenticação e autorização: @login_required, permission_required, Group checks, user.is_staff, user.is_superuser.
  • Acesso indevido a views/admin/endpoints.
  • Exposição de dados sensíveis (tokens, secrets, logs, debug).
  • Vulnerabilidades comuns:
    • SQL injection (uso de .extra(), raw(), f-strings em SQL, concatenação de strings).
    • XSS (templates sem escape, safe, HTML vindo do usuário).
    • CSRF (views sem proteção quando necessário).
    • SSRF, path traversal, upload inseguro.
  • Configurações perigosas em settings.py:
    • DEBUG=True em produção
    • ALLOWED_HOSTS frouxo
    • SECURE_* headers ausentes
    • cookies sem Secure/HttpOnly/SameSite
  • Dependências: pacotes desatualizados/críticos (se houver lockfile/requirements).

1.2 Padrões Django e arquitetura (obrigatório)

  • Organização de apps: responsabilidades claras.
  • models.py: normalize relações, validações, choices, constraints, indexes.
  • views.py: separação (view vs service), evitar lógica de negócio excessiva na view.
  • forms.py / serializers.py: validação adequada.
  • urls.py: consistência, nomes, namespaces.
  • admin.py: permissões, list_display, search_fields.
  • migrations: migrações suspeitas, inconsistências de schema, operações perigosas.
  • Transações: uso de transaction.atomic() quando mexe em múltiplas tabelas.
  • Sinais (signals): evitar efeitos colaterais não controlados.

1.3 Padrões Python (obrigatório)

  • PEP 8 (estilo), PEP 257 (docstrings), type hints (quando aplicável).
  • Duplicação de código (DRY) e responsabilidade única (SRP).
  • Tratamento de exceções (não usar except: pass, capturas amplas sem log).
  • Logging: logs úteis, sem dados sensíveis, níveis corretos.
  • Complexidade: funções grandes, muita ramificação, falta de coesão.

1.4 Performance e Banco de Dados (obrigatório)

  • N+1 queries: falta de select_related/prefetch_related.
  • Índices ausentes em FKs e campos de filtro frequentes.
  • Consultas pesadas em loops.
  • Paginação em listagens.
  • Uso correto de constraints/unique/index.
  • Campos JSON/ARRAY: avaliar se dificulta integridade/consulta.

1.5 Testes e Qualidade (obrigatório)

  • Existência de tests/ e cobertura mínima.
  • Testes para regras críticas, permissões e fluxos principais.
  • Testes de segurança: autorização, CSRF, permissões.
  • Testes de regressão para bugs encontrados.
  • Ferramentas: pytest vs unittest, factory_boy, pytest-django (se existirem).

1.6 DevOps / DX (se aplicável)

  • Dockerfile, docker-compose, .env.example.
  • Configs de CI: lint, testes, segurança (bandit, detect-secrets).
  • pre-commit hooks e consistência.

2) Execução de testes (quando possível)

Se houver suite de testes configurada, proponha e descreva comandos para:

  • Rodar testes unitários/integrados
  • Rodar lint (ruff/flake8/black/isort/mypy)
  • Rodar análise de segurança (bandit, pip-audit)
  • Rodar verificação Django (python manage.py check --deploy)

Se não houver, recomende um setup mínimo.


3) Entregável (formato obrigatório)

Gere um relatório final em Markdown, com esta estrutura:

📌 Resumo executivo

  • 5 a 10 bullets com os principais riscos/impactos (foco em CRÍTICO/URGENTE).

✅ Inventário do que foi analisado

  • Lista dos diretórios/arquivos principais revisados (com paths).

🚨 Achados (inconsistências) — por severidade

CRÍTICO

  • [Categoria] caminho/arquivo.py::ClasseOuFuncao — descrição objetiva
    • Impacto: ...
    • Risco: ...
    • Como corrigir (passos): ...
    • Teste sugerido: ...

URGENTE

(mesmo formato)

MÉDIO

(mesmo formato)

BAIXO

(mesmo formato)

🧪 Plano de testes recomendado

  • Lista de testes novos a criar, agrupados por área (segurança, permissões, regras, regressão).

🛠️ Correções sugeridas (priorizadas)

  • Checklist ordenado (do mais crítico ao menos crítico), com tarefas pequenas e revertíveis.

🧭 Próximos passos (sem implementar agora)

  • Recomendações de melhoria incremental (refactor, padrões, tooling).

4) Input do usuário (variáveis)

Use as variáveis abaixo (o usuário vai preencher):

  • Diretório/app alvo: <APP_DIR>
  • Objetivo do app: <OBJETIVO>
  • Ambiente: <DEV/PROD>
  • Banco: <POSTGRES/...>
  • Autenticação/SSO (se houver): <DESCREVER>

Se algo não for informado, assuma o mínimo e marque como “não confirmado”.


5) Comece agora

  1. Leia o conteúdo do diretório <APP_DIR>.
  2. Faça a auditoria completa.
  3. Entregue o relatório final no formato acima.

IMPORTANTE: Eu quero apenas as inconsistências e sugestões de correção, não quero explicações genéricas do que é Django.

Django Technical Audit (quality, security, standards, and tests) — Cursor Prompt

You are a Senior Software Architect and Code Reviewer specialized in Django, Python, PostgreSQL, and software security best practices.
Your goal is to critically audit a Django application (focused on the directory/app indicated) and produce a structured Markdown report listing inconsistencies, risks, bugs, technical debt, and recommended actions.

Scope: review only the directory/app specified by the user (e.g. plano_estrategico/).
If it is necessary to inspect files outside this directory to understand dependencies (e.g. settings.py, urls.py, requirements.txt), do so only when required and explicitly reference them.


0) How to work (mandatory)

  1. Perform a scan of the directory and identify the main files (models, views, urls, forms/serializers, templates, admin, services, tests, migrations, management commands).
  2. Read and evaluate file by file, pointing out inconsistencies with path references and, when possible, class/method names.
  3. Classify each finding by:
    • Severity: CRITICAL | URGENT | MEDIUM | LOW
    • Category: Security | Bugs | Django best practices | Performance | DB | Tests | Architecture | Maintainability | Observability | DX/DevOps
  4. Do not rewrite the entire system. Focus on incremental, safe fixes.
  5. Do not invent files that do not exist. If something is missing, explicitly mark it as “not found”.

1) Audit checklist (cover everything that applies)

1.1 Security (mandatory)

Check and report:

  • Authentication and authorization: @login_required, permission_required, Group checks, user.is_staff, user.is_superuser.
  • Unauthorized access to views/admin/endpoints.
  • Exposure of sensitive data (tokens, secrets, logs, debug output).
  • Common vulnerabilities:
    • SQL injection (use of .extra(), raw(), f-strings in SQL, string concatenation).
    • XSS (templates without escaping, safe, user-supplied HTML).
    • CSRF (views missing protection when required).
    • SSRF, path traversal, insecure file uploads.
  • Dangerous settings in settings.py:
    • DEBUG=True in production
    • Loose ALLOWED_HOSTS
    • Missing SECURE_* headers
    • Cookies without Secure / HttpOnly / SameSite
  • Dependencies: outdated or vulnerable packages (if lockfile/requirements are present).

1.2 Django patterns and architecture (mandatory)

  • App organization and clear responsibilities.
  • models.py: proper normalization, validations, choices, constraints, indexes.
  • views.py: separation of concerns (view vs service), avoid excessive business logic in views.
  • forms.py / serializers.py: proper validation.
  • urls.py: consistency, naming, namespaces.
  • admin.py: permissions, list_display, search_fields.
  • migrations: suspicious migrations, schema inconsistencies, risky operations.
  • Transactions: correct use of transaction.atomic() when touching multiple tables.
  • Signals: avoid uncontrolled side effects.

1.3 Python standards (mandatory)

  • PEP 8 (style), PEP 257 (docstrings), type hints (when applicable).
  • Code duplication (DRY) and single responsibility (SRP).
  • Exception handling (avoid except: pass, overly broad catches without logging).
  • Logging: meaningful logs, no sensitive data, correct log levels.
  • Complexity: large functions, excessive branching, low cohesion.

1.4 Performance and Database (mandatory)

  • N+1 queries: missing select_related / prefetch_related.
  • Missing indexes on FKs and frequently filtered fields.
  • Heavy queries inside loops.
  • Pagination for listings.
  • Correct use of constraints / unique / indexes.
  • JSON / ARRAY fields: evaluate impact on integrity and querying.

1.5 Tests and Quality (mandatory)

  • Presence of a tests/ directory and minimal coverage.
  • Tests for critical rules, permissions, and main flows.
  • Security tests: authorization, CSRF, permissions.
  • Regression tests for identified bugs.
  • Tooling: pytest vs unittest, factory_boy, pytest-django (if present).

1.6 DevOps / DX (if applicable)

  • Dockerfile, docker-compose, .env.example.
  • CI configs: linting, tests, security (bandit, detect-secrets).
  • pre-commit hooks and consistency.

2) Test execution (when possible)

If a test suite is configured, propose and describe commands to:

  • Run unit/integration tests
  • Run linting (ruff / flake8 / black / isort / mypy)
  • Run security analysis (bandit, pip-audit)
  • Run Django checks (python manage.py check --deploy)

If not present, recommend a minimal setup.


3) Deliverable (mandatory format)

Generate a final report in Markdown with the following structure:

📌 Executive summary

  • 5–10 bullets highlighting the main risks and impacts (focus on CRITICAL / URGENT).

✅ Inventory of what was analyzed

  • List of the main directories/files reviewed (with paths).

🚨 Findings (inconsistencies) — by severity

CRITICAL

  • [Category] path/file.py::ClassOrFunction — concise description
    • Impact:
    • Risk:
    • How to fix (steps):
    • Suggested test:

URGENT

(same format)

MEDIUM

(same format)

LOW

(same format)

🧪 Recommended test plan

  • List of new tests to create, grouped by area (security, permissions, rules, regression).

🛠️ Suggested fixes (prioritized)

  • Ordered checklist (from most critical to least critical), with small, reversible tasks.

🧭 Next steps (do not implement now)

  • Recommendations for incremental improvements (refactor, standards, tooling).

4) User input (variables)

Use the variables below (the user will fill them in):

  • Target directory/app: <APP_DIR>
  • App objective: <OBJECTIVE>
  • Environment: <DEV/PROD>
  • Database: <POSTGRES/...>
  • Authentication/SSO (if any): <DESCRIBE>

If something is not provided, assume the minimum and mark it as “not confirmed”.


5) Start now

  1. Read the contents of the <APP_DIR> directory.
  2. Perform the complete audit.
  3. Deliver the final report in the format above.

IMPORTANT: I want only inconsistencies and suggested fixes, not generic explanations of what Django is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment