refatoração de segurança e logs
This commit is contained in:
parent
6873b87a85
commit
663a8d5bf2
12 changed files with 362 additions and 37 deletions
150
.agent
Normal file
150
.agent
Normal file
|
|
@ -0,0 +1,150 @@
|
||||||
|
# arquivo: .agent
|
||||||
|
# Agente de desenvolvimento para o projeto e-li.nps
|
||||||
|
#
|
||||||
|
# Projeto:
|
||||||
|
# Widget NPS embutível via 1 arquivo JS + API em Go.
|
||||||
|
# Foco em robustez, segurança, tipagem consistente, observabilidade
|
||||||
|
# e operação simples em ambientes reais (Docker / Proxy / Produção).
|
||||||
|
|
||||||
|
agent_name: "quero_nps"
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Descrição do projeto (fonte de verdade)
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
project_description:
|
||||||
|
- "Widget NPS carregado via 1 arquivo JavaScript (e-li.nps.js)."
|
||||||
|
- "API HTTP escrita em Go."
|
||||||
|
- "PostgreSQL como banco de dados."
|
||||||
|
- "Painel administrativo opcional protegido por senha."
|
||||||
|
- "Uso por aplicações externas via <script>."
|
||||||
|
- "Fail-closed: se a API falhar, o widget não abre."
|
||||||
|
- "CORS liberado para uso amplo."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Stack
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
project_stack:
|
||||||
|
backend: "Go 1.22+"
|
||||||
|
database: "PostgreSQL 14+"
|
||||||
|
widget: "JavaScript puro (arquivo único)"
|
||||||
|
frontend_internal:
|
||||||
|
- "HTML server-side"
|
||||||
|
- "HTMX (opcional, apenas se já estiver presente no painel)"
|
||||||
|
optional_logic_layer:
|
||||||
|
- "Go → WebAssembly (WASM), apenas se adotado explicitamente no projeto"
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Regras gerais
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
rules:
|
||||||
|
- "Respeitar fielmente o comportamento descrito no README.md."
|
||||||
|
- "Não alterar contratos públicos do widget sem versionamento."
|
||||||
|
- "Evitar mudanças que quebrem widgets já embedados em clientes."
|
||||||
|
- "Mudanças que impactem desenvolvedores OU usuários DEVEM ser documentadas."
|
||||||
|
- "Código deve ser previsível, explícito e fácil de auditar."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Linguagem, nomes e comentários
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
naming_and_language:
|
||||||
|
- "Nomes de variáveis, funções e arquivos preferencialmente em português."
|
||||||
|
- "Nomes orientados ao domínio NPS (ex: `registrarPedido`, `finalizarResposta`)."
|
||||||
|
- "Comentários SEMPRE em português."
|
||||||
|
- "Comentários devem explicar regras de negócio e decisões técnicas."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Contratos e tipagens
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
typing_and_contracts:
|
||||||
|
- "Contratos de API devem ser explícitos e estáveis."
|
||||||
|
- "Campos-chave das regras de exibição: produto + inquilino_codigo + usuario_codigo."
|
||||||
|
- "Normalizações técnicas NÃO alteram valores exibidos ao usuário."
|
||||||
|
- "Tipagens JS/TS são auxiliares e não substituem validação no backend."
|
||||||
|
- "Validação SEMPRE no servidor."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Widget JavaScript
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
widget_policy:
|
||||||
|
- "Widget deve ser carregado via um único <script>."
|
||||||
|
- "Nenhuma dependência externa no cliente."
|
||||||
|
- "Cache controlado exclusivamente pelo servidor via ETag."
|
||||||
|
- "Browser sempre revalida o JS."
|
||||||
|
- "Se a API falhar, o widget NÃO deve abrir (fail-closed)."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Backend Go
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
backend_policy:
|
||||||
|
- "Servidor Go é a autoridade de regras e persistência."
|
||||||
|
- "Tabelas criadas automaticamente por produto: nps_{produto}."
|
||||||
|
- "Normalização de produto SOMENTE para uso técnico."
|
||||||
|
- "Nunca usar dados não normalizados em SQL."
|
||||||
|
- "Painel só habilita se SENHA_PAINEL estiver definida."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Segurança: prevenção de SQL Injection (OBRIGATÓRIO)
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
sql_injection_prevention:
|
||||||
|
- "NUNCA concatenar SQL com entrada do usuário."
|
||||||
|
- "Usar queries parametrizadas SEMPRE."
|
||||||
|
- "Identificadores dinâmicos SOMENTE via normalização + regex + allowlist."
|
||||||
|
- "Regex obrigatória: ^[a-z_][a-z0-9_]*$."
|
||||||
|
- "ORDER BY dinâmico apenas com colunas previamente definidas."
|
||||||
|
- "Toda decisão dinâmica de SQL deve ser comentada."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Observabilidade e logs (OBRIGATÓRIO)
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
logging_policy:
|
||||||
|
- "Registrar logs relevantes em toda a aplicação."
|
||||||
|
- "Logar: inicialização, rotas, chamadas de API, banco e erros."
|
||||||
|
- "Registrar tempo de execução das requisições."
|
||||||
|
- "Incluir IP real do usuário quando disponível."
|
||||||
|
- "Evitar log excessivo ou redundante."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Proteção de segredos nos logs (CRÍTICO)
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
secrets_policy:
|
||||||
|
- "NUNCA logar senhas, tokens, cookies, Authorization, secrets ou DSN."
|
||||||
|
- "Campos sensíveis devem ser omitidos ou mascarados."
|
||||||
|
- "Na dúvida, NÃO LOGAR."
|
||||||
|
- "Usar '[REDACTED]' quando necessário."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Proxy e IP real
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
proxy_policy:
|
||||||
|
- "Respeitar X-Forwarded-For e X-Real-IP."
|
||||||
|
- "Uso de middleware RealIP é obrigatório."
|
||||||
|
- "Persistir IP real para auditoria."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# README.md — regra OBRIGATÓRIA
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
readme_policy:
|
||||||
|
- "O README.md é a fonte de verdade operacional do projeto."
|
||||||
|
- "SE a mudança for IMPORTANTE para o DESENVOLVEDOR, atualizar o README.md."
|
||||||
|
- "SE a mudança for IMPORTANTE para o USUÁRIO, atualizar o README.md."
|
||||||
|
- "Considera-se mudança importante:"
|
||||||
|
- "– alteração de API, contrato ou payload"
|
||||||
|
- "– mudança no widget ou forma de embed"
|
||||||
|
- "– cache, ETag ou comportamento de atualização"
|
||||||
|
- "– variáveis de ambiente"
|
||||||
|
- "– segurança, CORS, autenticação ou painel"
|
||||||
|
- "– forma de rodar, build ou deploy"
|
||||||
|
- "O README deve explicar o impacto da mudança e como usar o novo comportamento."
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# Checklist final
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
checklist:
|
||||||
|
- "[ ] Compatível com widgets já publicados"
|
||||||
|
- "[ ] SQL 100% parametrizado"
|
||||||
|
- "[ ] Identificadores normalizados e validados"
|
||||||
|
- "[ ] Logs relevantes presentes"
|
||||||
|
- "[ ] Nenhum segredo em logs"
|
||||||
|
- "[ ] Cache do JS controlado por ETag"
|
||||||
|
- "[ ] README.md atualizado se a mudança impacta dev ou usuário"
|
||||||
|
- "[ ] Fluxo principal testado manualmente"
|
||||||
15
README.md
15
README.md
|
|
@ -341,13 +341,18 @@ curl -sS -X PATCH http://localhost:8080/api/e-li.nps/elicencie_gov/<id> \
|
||||||
- O nome **exibido ao usuário** é o original informado e fica salvo em `produto_nome` na tabela do produto.
|
- O nome **exibido ao usuário** é o original informado e fica salvo em `produto_nome` na tabela do produto.
|
||||||
- O controle de exibição (regras 45 dias / 10 dias) é baseado em: **produto + inquilino_codigo + usuario_codigo**.
|
- O controle de exibição (regras 45 dias / 10 dias) é baseado em: **produto + inquilino_codigo + usuario_codigo**.
|
||||||
|
|
||||||
## Recomendações (para prompts / manutenção)
|
### Observabilidade (logs)
|
||||||
|
|
||||||
Alguns cuidados:
|
O servidor registra **uma linha por requisição** com:
|
||||||
|
|
||||||
|
- `metodo`, `path`, `status`
|
||||||
|
- `dur_ms` (tempo de execução)
|
||||||
|
- `request_id` (quando disponível)
|
||||||
|
- `ip_real` (após `middleware.RealIP`)
|
||||||
|
|
||||||
|
Regra importante (segurança): o projeto **não** deve logar segredos (senha, tokens,
|
||||||
|
cookies, Authorization, DSN).
|
||||||
|
|
||||||
- Nomes de variáveis ou arquivos preferencialmente em português
|
|
||||||
- Sempre adicionar comentários em português que ajudem humanos e IAs na manutenção
|
|
||||||
- Se a mudança for importante, atualizar `README.md`
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
|
|
@ -20,8 +21,13 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// Load .env if present (convenience for local dev). Environment variables
|
// Logger estruturado (stdout). Mantemos log.Printf apenas para logs muito
|
||||||
// explicitly set in the OS take precedence.
|
// iniciais/críticos e para compatibilidade; o restante deve usar slog.
|
||||||
|
logger := elinps.LoggerPadrao()
|
||||||
|
slog.SetDefault(logger)
|
||||||
|
|
||||||
|
// Carrega .env se existir (conveniência para dev local).
|
||||||
|
// Variáveis definidas no SO têm precedência.
|
||||||
_ = godotenv.Load()
|
_ = godotenv.Load()
|
||||||
|
|
||||||
cfg := mustLoadConfig()
|
cfg := mustLoadConfig()
|
||||||
|
|
@ -35,7 +41,7 @@ func main() {
|
||||||
}
|
}
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Ensures required extensions exist.
|
// Garante extensões necessárias.
|
||||||
if err := db.EnsurePgcrypto(ctx, pool); err != nil {
|
if err := db.EnsurePgcrypto(ctx, pool); err != nil {
|
||||||
log.Fatalf("ensure pgcrypto: %v", err)
|
log.Fatalf("ensure pgcrypto: %v", err)
|
||||||
}
|
}
|
||||||
|
|
@ -44,23 +50,24 @@ func main() {
|
||||||
r.Use(middleware.RequestID)
|
r.Use(middleware.RequestID)
|
||||||
r.Use(middleware.RealIP)
|
r.Use(middleware.RealIP)
|
||||||
r.Use(middleware.Recoverer)
|
r.Use(middleware.Recoverer)
|
||||||
|
r.Use(elinps.MiddlewareLogRequisicao(logger))
|
||||||
r.Use(middleware.Timeout(15 * time.Second))
|
r.Use(middleware.Timeout(15 * time.Second))
|
||||||
r.Use(middleware.Compress(5))
|
r.Use(middleware.Compress(5))
|
||||||
|
|
||||||
// CORS wildcard + preflight
|
// CORS liberado + preflight.
|
||||||
r.Use(elinps.CORSMiddleware())
|
r.Use(elinps.CORSMiddleware())
|
||||||
|
|
||||||
// Basic limits
|
// Limites básicos.
|
||||||
r.Use(elinps.MaxBodyBytesMiddleware(64 * 1024))
|
r.Use(elinps.MaxBodyBytesMiddleware(64 * 1024))
|
||||||
|
|
||||||
// Health
|
// Health.
|
||||||
r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
|
r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
|
||||||
|
|
||||||
// Home: renderiza README.md
|
// Home: renderiza README.md
|
||||||
// Público (sem senha), para facilitar documentação do serviço.
|
// Público (sem senha), para facilitar documentação do serviço.
|
||||||
r.Get("/", elinps.NewReadmePage("README.md").ServeHTTP)
|
r.Get("/", elinps.NewReadmePage("README.md").ServeHTTP)
|
||||||
|
|
||||||
// Static widget
|
// Widget estático.
|
||||||
fileServer := http.FileServer(http.Dir("web/static"))
|
fileServer := http.FileServer(http.Dir("web/static"))
|
||||||
// Versão do widget para controle de cache.
|
// Versão do widget para controle de cache.
|
||||||
//
|
//
|
||||||
|
|
@ -87,12 +94,12 @@ func main() {
|
||||||
})
|
})
|
||||||
r.Handle("/*", http.StripPrefix("/static/", fileServer))
|
r.Handle("/*", http.StripPrefix("/static/", fileServer))
|
||||||
})
|
})
|
||||||
// Convenience: allow /teste.html
|
// Conveniência: permitir /teste.html
|
||||||
r.Get("/teste.html", func(w http.ResponseWriter, r *http.Request) {
|
r.Get("/teste.html", func(w http.ResponseWriter, r *http.Request) {
|
||||||
http.ServeFile(w, r, "web/static/teste.html")
|
http.ServeFile(w, r, "web/static/teste.html")
|
||||||
})
|
})
|
||||||
|
|
||||||
// NPS routes
|
// Rotas NPS.
|
||||||
h := elinps.NewHandlers(pool)
|
h := elinps.NewHandlers(pool)
|
||||||
r.Route("/api/e-li.nps", func(r chi.Router) {
|
r.Route("/api/e-li.nps", func(r chi.Router) {
|
||||||
r.Post("/pedido", h.PostPedido)
|
r.Post("/pedido", h.PostPedido)
|
||||||
|
|
@ -103,7 +110,7 @@ func main() {
|
||||||
r.Get("/{produto}/{id}/form", h.GetForm)
|
r.Get("/{produto}/{id}/form", h.GetForm)
|
||||||
})
|
})
|
||||||
|
|
||||||
// Painel (dashboard)
|
// Painel.
|
||||||
// Protegido por SENHA_PAINEL.
|
// Protegido por SENHA_PAINEL.
|
||||||
// Se SENHA_PAINEL estiver vazia, o painel fica desabilitado.
|
// Se SENHA_PAINEL estiver vazia, o painel fica desabilitado.
|
||||||
painel := elinps.NewPainelHandlers(pool, cfg.SenhaPainel)
|
painel := elinps.NewPainelHandlers(pool, cfg.SenhaPainel)
|
||||||
|
|
@ -116,7 +123,7 @@ func main() {
|
||||||
}
|
}
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
log.Printf("listening on %s", cfg.Addr)
|
logger.Info("servidor_iniciado", "addr", cfg.Addr)
|
||||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||||
log.Fatalf("listen: %v", err)
|
log.Fatalf("listen: %v", err)
|
||||||
}
|
}
|
||||||
|
|
@ -126,9 +133,9 @@ func main() {
|
||||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||||
log.Printf("shutdown: %v", err)
|
logger.Error("erro_no_shutdown", "err", err)
|
||||||
}
|
}
|
||||||
log.Printf("bye")
|
logger.Info("servidor_finalizado")
|
||||||
}
|
}
|
||||||
|
|
||||||
type config struct {
|
type config struct {
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
|
||||||
return nil, fmt.Errorf("parse DATABASE_URL: %w", err)
|
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.MaxConns = 10
|
||||||
cfg.MinConns = 0
|
cfg.MinConns = 0
|
||||||
cfg.MaxConnLifetime = 60 * time.Minute
|
cfg.MaxConnLifetime = 60 * time.Minute
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,22 @@ import (
|
||||||
|
|
||||||
var produtoRe = regexp.MustCompile(`^[a-z_][a-z0-9_]*$`)
|
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:
|
// NormalizeProduto normaliza e valida um nome de produto para uso em:
|
||||||
// - nomes de tabela no Postgres (prefixo nps_)
|
// - nomes de tabela no Postgres (prefixo nps_)
|
||||||
// - rotas/URLs (parâmetro {produto})
|
// - rotas/URLs (parâmetro {produto})
|
||||||
|
|
@ -80,11 +96,14 @@ func EnsurePgcrypto(ctx context.Context, pool *pgxpool.Pool) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// EnsureNPSTable creates the per-product table + indexes if they do not exist.
|
// EnsureNPSTable cria a tabela por produto + índices se não existirem.
|
||||||
// IMPORTANT: tableName must be created from a sanitized product name.
|
// Importante: tableName deve ser criada a partir de um produto normalizado.
|
||||||
func EnsureNPSTable(ctx context.Context, pool *pgxpool.Pool, tableName string) error {
|
func EnsureNPSTable(ctx context.Context, pool *pgxpool.Pool, tableName string) error {
|
||||||
// Identifiers cannot be passed as $1 parameters, so we must interpolate.
|
// 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(`
|
q := fmt.Sprintf(`
|
||||||
CREATE TABLE IF NOT EXISTS %s (
|
CREATE TABLE IF NOT EXISTS %s (
|
||||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ package elinps
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
|
@ -38,21 +39,22 @@ func (h *Handlers) PostPedido(w http.ResponseWriter, r *http.Request) {
|
||||||
return
|
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)
|
table, err := h.store.EnsureTableForProduto(ctx, in.ProdutoNome)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "produto_invalido"})
|
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "produto_invalido"})
|
||||||
return
|
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
|
// table = "nps_" + produto_normalizado
|
||||||
produtoNormalizado := strings.TrimPrefix(table, "nps_")
|
produtoNormalizado := strings.TrimPrefix(table, "nps_")
|
||||||
|
|
||||||
// Rules
|
// Regras.
|
||||||
respRecente, err := h.store.HasRespostaValidaRecente(ctx, table, in.InquilinoCodigo, in.UsuarioCodigo)
|
respRecente, err := h.store.HasRespostaValidaRecente(ctx, table, in.InquilinoCodigo, in.UsuarioCodigo)
|
||||||
if err != nil {
|
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"})
|
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "erro"})
|
||||||
return
|
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)
|
pedidoAberto, err := h.store.HasPedidoEmAbertoRecente(ctx, table, in.InquilinoCodigo, in.UsuarioCodigo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
slog.Error("erro ao checar pedido em aberto", "err", err)
|
||||||
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "erro"})
|
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "erro"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
@ -73,6 +76,7 @@ func (h *Handlers) PostPedido(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
id, err := h.store.CreatePedido(ctx, table, in, r)
|
id, err := h.store.CreatePedido(ctx, table, in, r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
slog.Error("erro ao criar pedido", "err", err)
|
||||||
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "erro"})
|
writeJSON(w, http.StatusOK, PedidoResponse{PodeAbrir: false, Motivo: "erro"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
@ -85,7 +89,7 @@ func (h *Handlers) PatchResposta(w http.ResponseWriter, r *http.Request) {
|
||||||
produtoParam := chi.URLParam(r, "produto")
|
produtoParam := chi.URLParam(r, "produto")
|
||||||
id := chi.URLParam(r, "id")
|
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)
|
prod, err := db.NormalizeProduto(produtoParam)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "produto_invalido"})
|
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)
|
table := db.TableNameForProduto(prod)
|
||||||
if err := db.EnsureNPSTable(ctx, h.store.pool, table); err != nil {
|
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"})
|
writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "db"})
|
||||||
return
|
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 {
|
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"})
|
writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "db"})
|
||||||
return
|
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" {
|
if r.Header.Get("HX-Request") == "true" {
|
||||||
reg, err := h.store.GetRegistro(ctx, table, id)
|
reg, err := h.store.GetRegistro(ctx, table, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
slog.Error("erro ao buscar registro", "err", err)
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
w.Write([]byte("db"))
|
w.Write([]byte("db"))
|
||||||
return
|
return
|
||||||
|
|
@ -147,6 +154,7 @@ func (h *Handlers) GetForm(w http.ResponseWriter, r *http.Request) {
|
||||||
}
|
}
|
||||||
table := db.TableNameForProduto(prod)
|
table := db.TableNameForProduto(prod)
|
||||||
if err := db.EnsureNPSTable(ctx, h.store.pool, table); err != nil {
|
if err := db.EnsureNPSTable(ctx, h.store.pool, table); err != nil {
|
||||||
|
slog.Error("erro ao garantir tabela", "err", err)
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
w.Write([]byte("db"))
|
w.Write([]byte("db"))
|
||||||
return
|
return
|
||||||
|
|
@ -159,6 +167,7 @@ func (h *Handlers) GetForm(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Write([]byte("nao encontrado"))
|
w.Write([]byte("nao encontrado"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
slog.Error("erro ao buscar registro", "err", err)
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
w.Write([]byte("db"))
|
w.Write([]byte("db"))
|
||||||
return
|
return
|
||||||
|
|
@ -170,8 +179,8 @@ func (h *Handlers) GetForm(w http.ResponseWriter, r *http.Request) {
|
||||||
Reg: reg,
|
Reg: reg,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Always return a standalone HTML page so the widget can use iframe.
|
// Sempre retornamos uma página HTML completa para o widget usar iframe.
|
||||||
// But the inner container is also HTMX-friendly (it swaps itself).
|
// 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")
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
h.tpl.Render(w, "form_page.html", data)
|
h.tpl.Render(w, "form_page.html", data)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
91
internal/elinps/logging.go
Normal file
91
internal/elinps/logging.go
Normal 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)
|
||||||
|
}
|
||||||
|
|
@ -6,6 +6,8 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"e-li.nps/internal/db"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -42,7 +44,10 @@ ORDER BY tablename`)
|
||||||
// - 7–8 neutros
|
// - 7–8 neutros
|
||||||
// - 9–10 promotores
|
// - 9–10 promotores
|
||||||
func (s *Store) NPSMesAMes(ctx context.Context, tabela string, meses int) ([]NPSMensal, error) {
|
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(`
|
q := fmt.Sprintf(`
|
||||||
WITH base AS (
|
WITH base AS (
|
||||||
SELECT
|
SELECT
|
||||||
|
|
@ -103,6 +108,11 @@ func (f *ListarRespostasFiltro) normalizar() {
|
||||||
|
|
||||||
// ListarRespostas retorna respostas respondidas, com paginação e filtro.
|
// ListarRespostas retorna respostas respondidas, com paginação e filtro.
|
||||||
func (s *Store) ListarRespostas(ctx context.Context, tabela string, filtro ListarRespostasFiltro) ([]RespostaPainel, error) {
|
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()
|
filtro.normalizar()
|
||||||
offset := (filtro.Pagina - 1) * filtro.PorPagina
|
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"
|
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(`
|
q := fmt.Sprintf(`
|
||||||
SELECT
|
SELECT
|
||||||
id,
|
id,
|
||||||
|
|
|
||||||
|
|
@ -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) {
|
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(`
|
q := fmt.Sprintf(`
|
||||||
SELECT 1
|
SELECT 1
|
||||||
FROM %s
|
FROM %s
|
||||||
|
|
@ -72,6 +76,10 @@ LIMIT 1`, table)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) HasPedidoEmAbertoRecente(ctx context.Context, table, inquilinoCodigo, usuarioCodigo string) (bool, error) {
|
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(`
|
q := fmt.Sprintf(`
|
||||||
SELECT 1
|
SELECT 1
|
||||||
FROM %s
|
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) {
|
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(`
|
q := fmt.Sprintf(`
|
||||||
INSERT INTO %s (
|
INSERT INTO %s (
|
||||||
produto_nome,
|
produto_nome,
|
||||||
|
|
@ -111,6 +123,10 @@ RETURNING id`, table)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) GetRegistro(ctx context.Context, table, id string) (Registro, error) {
|
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(`
|
q := fmt.Sprintf(`
|
||||||
SELECT id, produto_nome, status, nota, justificativa, pedido_criado_em, respondido_em
|
SELECT id, produto_nome, status, nota, justificativa, pedido_criado_em, respondido_em
|
||||||
FROM %s
|
FROM %s
|
||||||
|
|
@ -124,6 +140,10 @@ WHERE id=$1`, table)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) PatchRegistro(ctx context.Context, table, id string, in PatchInput) error {
|
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.
|
// UPDATE único com campos opcionais.
|
||||||
q := fmt.Sprintf(`
|
q := fmt.Sprintf(`
|
||||||
UPDATE %s
|
UPDATE %s
|
||||||
|
|
@ -140,6 +160,10 @@ WHERE id=$1`, table)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) TouchAtualizadoEm(ctx context.Context, table, id string) error {
|
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)
|
q := fmt.Sprintf(`UPDATE %s SET atualizado_em=now() WHERE id=$1`, table)
|
||||||
_, err := s.pool.Exec(ctx, q, id)
|
_, err := s.pool.Exec(ctx, q, id)
|
||||||
return err
|
return err
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ package elinps
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"html/template"
|
"html/template"
|
||||||
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -12,7 +13,14 @@ type TemplateRenderer struct {
|
||||||
func NewTemplateRenderer(t *template.Template) *TemplateRenderer { return &TemplateRenderer{t: t} }
|
func NewTemplateRenderer(t *template.Template) *TemplateRenderer { return &TemplateRenderer{t: t} }
|
||||||
|
|
||||||
func (r *TemplateRenderer) Render(w http.ResponseWriter, name string, data any) {
|
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 {
|
type FormPageData struct {
|
||||||
|
|
|
||||||
|
|
@ -7,9 +7,8 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func mustParseTemplates() *template.Template {
|
func mustParseTemplates() *template.Template {
|
||||||
// Local filesystem parsing (keeps the repo simple).
|
// Parse de templates via filesystem local (mantém o repositório simples).
|
||||||
// If you want a single-binary deploy, we can switch to go:embed by moving
|
// Se precisarmos de deploy single-binary, podemos migrar para go:embed.
|
||||||
// templates into internal/elinps and embedding without "..".
|
|
||||||
funcs := template.FuncMap{
|
funcs := template.FuncMap{
|
||||||
"seq": func(start, end int) []int {
|
"seq": func(start, end int) []int {
|
||||||
if end < start {
|
if end < start {
|
||||||
|
|
@ -25,7 +24,7 @@ func mustParseTemplates() *template.Template {
|
||||||
return ptr != nil && *ptr == v
|
return ptr != nil && *ptr == v
|
||||||
},
|
},
|
||||||
"produtoLabel": func(produto string) string {
|
"produtoLabel": func(produto string) string {
|
||||||
// Best-effort label from normalized produto.
|
// Label "amigável" a partir do produto normalizado.
|
||||||
p := strings.ReplaceAll(produto, "_", " ")
|
p := strings.ReplaceAll(produto, "_", " ")
|
||||||
parts := strings.Fields(p)
|
parts := strings.Fields(p)
|
||||||
for i := range parts {
|
for i := range parts {
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
{{define "form_inner.html"}}
|
{{define "form_inner.html"}}
|
||||||
{{/* This block can be swapped by HTMX (target #eli-nps-modal-body) */}}
|
{{/* Este bloco pode ser trocado pelo HTMX (target #eli-nps-modal-body) */}}
|
||||||
{{if eq .Reg.Status "respondido"}}
|
{{if eq .Reg.Status "respondido"}}
|
||||||
<div class="eli-nps-ok">
|
<div class="eli-nps-ok">
|
||||||
<p class="eli-nps-title">Obrigado!</p>
|
<p class="eli-nps-title">Obrigado!</p>
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue