refatoração de segurança e logs

This commit is contained in:
Luiz Silva 2026-01-01 19:13:24 -03:00
parent 6873b87a85
commit 663a8d5bf2
12 changed files with 362 additions and 37 deletions

View file

@ -14,7 +14,7 @@ func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
return nil, fmt.Errorf("parse DATABASE_URL: %w", err)
}
// Reasonable defaults
// Defaults razoáveis para um serviço pequeno/médio.
cfg.MaxConns = 10
cfg.MinConns = 0
cfg.MaxConnLifetime = 60 * time.Minute

View file

@ -13,6 +13,22 @@ import (
var produtoRe = regexp.MustCompile(`^[a-z_][a-z0-9_]*$`)
// TableNameValido valida se o nome de tabela está no formato esperado do projeto:
// "nps_" + produto normalizado.
//
// Motivação (segurança): identificadores não podem ser parametrizados em SQL.
// Então, sempre que precisarmos interpolar um nome de tabela, validamos aqui
// para evitar SQL injection via identificador.
func TableNameValido(tableName string) bool {
if !strings.HasPrefix(tableName, "nps_") {
return false
}
produto := strings.TrimPrefix(tableName, "nps_")
// produtoRe já garante: ^[a-z_][a-z0-9_]*$
// (e a normalização limita tamanho em NormalizeProduto).
return produtoRe.MatchString(produto)
}
// NormalizeProduto normaliza e valida um nome de produto para uso em:
// - nomes de tabela no Postgres (prefixo nps_)
// - rotas/URLs (parâmetro {produto})
@ -80,11 +96,14 @@ func EnsurePgcrypto(ctx context.Context, pool *pgxpool.Pool) error {
return err
}
// EnsureNPSTable creates the per-product table + indexes if they do not exist.
// IMPORTANT: tableName must be created from a sanitized product name.
// EnsureNPSTable cria a tabela por produto + índices se não existirem.
// Importante: tableName deve ser criada a partir de um produto normalizado.
func EnsureNPSTable(ctx context.Context, pool *pgxpool.Pool, tableName string) error {
// Identifiers cannot be passed as $1 parameters, so we must interpolate.
// Safety: tableName is strictly derived from NormalizeProduto + prefix.
// Segurança: tableName deve ser estritamente derivada de NormalizeProduto + prefix.
if !TableNameValido(tableName) {
return fmt.Errorf("nome de tabela invalido")
}
q := fmt.Sprintf(`
CREATE TABLE IF NOT EXISTS %s (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),

View file

@ -3,6 +3,7 @@ package elinps
import (
"encoding/json"
"errors"
"log/slog"
"net/http"
"strings"
@ -38,21 +39,22 @@ func (h *Handlers) PostPedido(w http.ResponseWriter, r *http.Request) {
return
}
// Ensure per-product table exists (also normalizes produto).
// Garante a tabela do produto (e normaliza o identificador técnico).
table, err := h.store.EnsureTableForProduto(ctx, in.ProdutoNome)
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "produto_invalido"})
return
}
// Keep normalized form for the widget to build URLs safely.
// Mantemos a forma normalizada para o widget montar URLs com segurança.
// table = "nps_" + produto_normalizado
produtoNormalizado := strings.TrimPrefix(table, "nps_")
// Rules
// Regras.
respRecente, err := h.store.HasRespostaValidaRecente(ctx, table, in.InquilinoCodigo, in.UsuarioCodigo)
if err != nil {
// Fail-closed
slog.Error("erro ao checar resposta recente", "err", err)
// Fail-closed.
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "erro"})
return
}
@ -63,6 +65,7 @@ func (h *Handlers) PostPedido(w http.ResponseWriter, r *http.Request) {
pedidoAberto, err := h.store.HasPedidoEmAbertoRecente(ctx, table, in.InquilinoCodigo, in.UsuarioCodigo)
if err != nil {
slog.Error("erro ao checar pedido em aberto", "err", err)
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "erro"})
return
}
@ -73,6 +76,7 @@ func (h *Handlers) PostPedido(w http.ResponseWriter, r *http.Request) {
id, err := h.store.CreatePedido(ctx, table, in, r)
if err != nil {
slog.Error("erro ao criar pedido", "err", err)
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "erro"})
return
}
@ -85,7 +89,7 @@ func (h *Handlers) PatchResposta(w http.ResponseWriter, r *http.Request) {
produtoParam := chi.URLParam(r, "produto")
id := chi.URLParam(r, "id")
// produtoParam already in path; sanitize again.
// produtoParam já está no path; sanitizamos novamente por segurança.
prod, err := db.NormalizeProduto(produtoParam)
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "produto_invalido"})
@ -93,6 +97,7 @@ func (h *Handlers) PatchResposta(w http.ResponseWriter, r *http.Request) {
}
table := db.TableNameForProduto(prod)
if err := db.EnsureNPSTable(ctx, h.store.pool, table); err != nil {
slog.Error("erro ao garantir tabela", "err", err)
writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "db"})
return
}
@ -113,14 +118,16 @@ func (h *Handlers) PatchResposta(w http.ResponseWriter, r *http.Request) {
}
if err := h.store.PatchRegistro(ctx, table, id, in); err != nil {
slog.Error("erro ao atualizar registro", "err", err)
writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "db"})
return
}
// If called via HTMX, respond with refreshed HTML fragment.
// Se chamado via HTMX, respondemos com fragmento HTML atualizado.
if r.Header.Get("HX-Request") == "true" {
reg, err := h.store.GetRegistro(ctx, table, id)
if err != nil {
slog.Error("erro ao buscar registro", "err", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("db"))
return
@ -147,6 +154,7 @@ func (h *Handlers) GetForm(w http.ResponseWriter, r *http.Request) {
}
table := db.TableNameForProduto(prod)
if err := db.EnsureNPSTable(ctx, h.store.pool, table); err != nil {
slog.Error("erro ao garantir tabela", "err", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("db"))
return
@ -159,6 +167,7 @@ func (h *Handlers) GetForm(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("nao encontrado"))
return
}
slog.Error("erro ao buscar registro", "err", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("db"))
return
@ -170,8 +179,8 @@ func (h *Handlers) GetForm(w http.ResponseWriter, r *http.Request) {
Reg: reg,
}
// Always return a standalone HTML page so the widget can use iframe.
// But the inner container is also HTMX-friendly (it swaps itself).
// Sempre retornamos uma página HTML completa para o widget usar iframe.
// Porém o container interno também é compatível com HTMX (swap de si mesmo).
w.Header().Set("Content-Type", "text/html; charset=utf-8")
h.tpl.Render(w, "form_page.html", data)
}

View file

@ -0,0 +1,91 @@
package elinps
import (
"context"
"log/slog"
"net"
"net/http"
"os"
"time"
"github.com/go-chi/chi/v5/middleware"
)
// LoggerPadrao cria um logger simples (stdout) adequado para Docker.
//
// Regras do projeto:
// - logs relevantes (rotas, tempo de execução, erros)
// - NUNCA logar segredos (Authorization/cookies/senha/DSN)
func LoggerPadrao() *slog.Logger {
return slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
}
type responseWriterComStatus struct {
http.ResponseWriter
status int
bytes int
}
func (w *responseWriterComStatus) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func (w *responseWriterComStatus) Write(b []byte) (int, error) {
if w.status == 0 {
w.status = http.StatusOK
}
n, err := w.ResponseWriter.Write(b)
w.bytes += n
return n, err
}
// MiddlewareLogRequisicao registra uma linha por requisição com:
// - método, path, status, duração
// - request_id (se existir)
// - ip_real (após chi/middleware.RealIP)
func MiddlewareLogRequisicao(logger *slog.Logger) func(http.Handler) http.Handler {
if logger == nil {
logger = slog.Default()
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ini := time.Now()
ww := &responseWriterComStatus{ResponseWriter: w}
next.ServeHTTP(ww, r)
dur := time.Since(ini)
attrs := []any{
"metodo", r.Method,
"path", r.URL.Path,
"status", ww.status,
"dur_ms", dur.Milliseconds(),
"bytes", ww.bytes,
"ip_real", ipSomenteHost(r.RemoteAddr),
}
if reqID := requestIDFromContext(r.Context()); reqID != "" {
attrs = append(attrs, "request_id", reqID)
}
logger.Info("http_request", attrs...)
})
}
}
// ipSomenteHost retorna apenas o IP (sem porta). Se o valor não parecer um IP,
// devolve string vazia.
func ipSomenteHost(remoteAddr string) string {
ip := remoteAddr
if host, _, err := net.SplitHostPort(remoteAddr); err == nil {
ip = host
}
if net.ParseIP(ip) == nil {
return ""
}
return ip
}
func requestIDFromContext(ctx context.Context) string {
// O chi/middleware.RequestID coloca o ID no context.
return middleware.GetReqID(ctx)
}

View file

@ -6,6 +6,8 @@ import (
"strings"
"time"
"e-li.nps/internal/db"
"github.com/jackc/pgx/v5"
)
@ -42,7 +44,10 @@ ORDER BY tablename`)
// - 78 neutros
// - 910 promotores
func (s *Store) NPSMesAMes(ctx context.Context, tabela string, meses int) ([]NPSMensal, error) {
// Segurança: tabela deve ser derivada de NormalizeProduto + prefixo.
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
if !db.TableNameValido(tabela) {
return nil, fmt.Errorf("tabela invalida")
}
q := fmt.Sprintf(`
WITH base AS (
SELECT
@ -103,6 +108,11 @@ func (f *ListarRespostasFiltro) normalizar() {
// ListarRespostas retorna respostas respondidas, com paginação e filtro.
func (s *Store) ListarRespostas(ctx context.Context, tabela string, filtro ListarRespostasFiltro) ([]RespostaPainel, error) {
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
if !db.TableNameValido(tabela) {
return nil, fmt.Errorf("tabela invalida")
}
filtro.normalizar()
offset := (filtro.Pagina - 1) * filtro.PorPagina
@ -111,6 +121,9 @@ func (s *Store) ListarRespostas(ctx context.Context, tabela string, filtro Lista
cond += " AND nota BETWEEN 1 AND 6"
}
// Importante (segurança): apesar do cond ser construído em string, ele NÃO usa
// entrada do usuário diretamente. O filtro "SomenteNotasBaixas" é booleano.
// A tabela também é validada por regex (TableNameValido).
q := fmt.Sprintf(`
SELECT
id,

View file

@ -52,6 +52,10 @@ func (s *Store) EnsureTableForProduto(ctx context.Context, produtoNome string) (
}
func (s *Store) HasRespostaValidaRecente(ctx context.Context, table, inquilinoCodigo, usuarioCodigo string) (bool, error) {
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
if !db.TableNameValido(table) {
return false, fmt.Errorf("tabela invalida")
}
q := fmt.Sprintf(`
SELECT 1
FROM %s
@ -72,6 +76,10 @@ LIMIT 1`, table)
}
func (s *Store) HasPedidoEmAbertoRecente(ctx context.Context, table, inquilinoCodigo, usuarioCodigo string) (bool, error) {
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
if !db.TableNameValido(table) {
return false, fmt.Errorf("tabela invalida")
}
q := fmt.Sprintf(`
SELECT 1
FROM %s
@ -91,6 +99,10 @@ LIMIT 1`, table)
}
func (s *Store) CreatePedido(ctx context.Context, table string, in PedidoInput, r *http.Request) (string, error) {
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
if !db.TableNameValido(table) {
return "", fmt.Errorf("tabela invalida")
}
q := fmt.Sprintf(`
INSERT INTO %s (
produto_nome,
@ -111,6 +123,10 @@ RETURNING id`, table)
}
func (s *Store) GetRegistro(ctx context.Context, table, id string) (Registro, error) {
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
if !db.TableNameValido(table) {
return Registro{}, fmt.Errorf("tabela invalida")
}
q := fmt.Sprintf(`
SELECT id, produto_nome, status, nota, justificativa, pedido_criado_em, respondido_em
FROM %s
@ -124,6 +140,10 @@ WHERE id=$1`, table)
}
func (s *Store) PatchRegistro(ctx context.Context, table, id string, in PatchInput) error {
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
if !db.TableNameValido(table) {
return fmt.Errorf("tabela invalida")
}
// UPDATE único com campos opcionais.
q := fmt.Sprintf(`
UPDATE %s
@ -140,6 +160,10 @@ WHERE id=$1`, table)
}
func (s *Store) TouchAtualizadoEm(ctx context.Context, table, id string) error {
// Segurança: a tabela é um identificador interpolado. Validamos sempre.
if !db.TableNameValido(table) {
return fmt.Errorf("tabela invalida")
}
q := fmt.Sprintf(`UPDATE %s SET atualizado_em=now() WHERE id=$1`, table)
_, err := s.pool.Exec(ctx, q, id)
return err

View file

@ -2,6 +2,7 @@ package elinps
import (
"html/template"
"log/slog"
"net/http"
)
@ -12,7 +13,14 @@ type TemplateRenderer struct {
func NewTemplateRenderer(t *template.Template) *TemplateRenderer { return &TemplateRenderer{t: t} }
func (r *TemplateRenderer) Render(w http.ResponseWriter, name string, data any) {
_ = r.t.ExecuteTemplate(w, name, data)
if err := r.t.ExecuteTemplate(w, name, data); err != nil {
// Não expomos detalhes do erro para o usuário (pode conter paths/etc).
// Mas registramos para depuração.
slog.Error("erro ao renderizar template", "template", name, "err", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("erro ao renderizar"))
return
}
}
type FormPageData struct {

View file

@ -7,9 +7,8 @@ import (
)
func mustParseTemplates() *template.Template {
// Local filesystem parsing (keeps the repo simple).
// If you want a single-binary deploy, we can switch to go:embed by moving
// templates into internal/elinps and embedding without "..".
// Parse de templates via filesystem local (mantém o repositório simples).
// Se precisarmos de deploy single-binary, podemos migrar para go:embed.
funcs := template.FuncMap{
"seq": func(start, end int) []int {
if end < start {
@ -25,7 +24,7 @@ func mustParseTemplates() *template.Template {
return ptr != nil && *ptr == v
},
"produtoLabel": func(produto string) string {
// Best-effort label from normalized produto.
// Label "amigável" a partir do produto normalizado.
p := strings.ReplaceAll(produto, "_", " ")
parts := strings.Fields(p)
for i := range parts {