Fiber: ImmutableLog
Middleware para o Fiber v2. Usa c.Next() para capturar o erro e derivar o status, c.Locals() para eventos customizados e goroutine fire-and-forget para zero overhead. Inclui tratamento correto do buffer recycling do fasthttp.
Código do middleware
O Fiber usa fasthttp internamente (não net/http). O middleware copia o body antes de c.Next() porque o Fiber recicla buffers após cada requisição, e copia todos os dados da requisição (snapshot) antes de abrir a goroutine.
Nunca leia o *fiber.Ctx dentro da goroutine. O Fiber devolve o Ctx ao pool assim que o handler retorna; qualquer leitura depois disso (c.Get, c.Path, c.IP, c.Route) causa SIGSEGV, que o recover() não captura e derruba o processo inteiro. Por isso o middleware copia tudo para um snapshot dentro do handler e passa só o snapshot à goroutine.
package immutablelog
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/utils"
)
const fiberEventNameKey = "imtbl.eventName"
const fiberTrailKey = "imtbl.trail"
type Config struct {
APIKey string
ServiceName string
Env string
APIURL string
SkipPaths []string
// Timezone do cliente - usado pelo dashboard para exibir os timestamps.
// Client timezone - used by the dashboard to render timestamps.
ClientTZ string
ClientOffsetMinutes int
}
// sanitizeTrail normaliza o immutable_trail conforme as regras do servidor:
// trim, nao-vazio, max 256 chars, sem ':' (o servidor responde 400 se violado).
func sanitizeTrail(v string) string {
v = strings.TrimSpace(v)
if v == "" {
return ""
}
v = strings.ReplaceAll(v, ":", "-")
if len(v) > 256 {
v = v[:256]
}
return v
}
// New returns a fiber.Handler middleware that sends an audit event to ImmutableLog.
// The event is sent asynchronously via a goroutine - never blocks the response.
func New(cfg Config) fiber.Handler {
if cfg.APIURL == "" {
cfg.APIURL = "https://api.immutablelog.com"
}
if cfg.APIKey == "" {
cfg.APIKey = os.Getenv("IMTBL_API_KEY")
}
if cfg.ServiceName == "" {
cfg.ServiceName = os.Getenv("IMTBL_SERVICE_NAME")
}
if cfg.Env == "" {
cfg.Env = os.Getenv("IMTBL_ENV")
}
if cfg.ClientTZ == "" {
cfg.ClientTZ = "America/Sao_Paulo"
}
if cfg.ClientOffsetMinutes == 0 {
cfg.ClientOffsetMinutes = -180
}
skipSet := make(map[string]struct{}, len(cfg.SkipPaths))
for _, p := range cfg.SkipPaths {
skipSet[p] = struct{}{}
}
return func(c *fiber.Ctx) error {
if _, skip := skipSet[c.Path()]; skip {
return c.Next()
}
startedAt := time.Now()
// Copy body BEFORE c.Next() - Fiber recycles the buffer after the request
bodyBytes := make([]byte, len(c.Body()))
copy(bodyBytes, c.Body())
// Execute all downstream handlers
err := c.Next()
elapsed := time.Since(startedAt)
// Com erro, o ErrorHandler ainda nao escreveu a resposta: derive o status do erro.
// On error the ErrorHandler has not written the response yet: derive the status from the error.
status := responseStatus(c, err)
// Custom event name set by a handler via c.Locals(fiberEventNameKey, "...")
// Copied: a handler may have stored a zero-copy string taken from the Ctx.
eventName, _ := c.Locals(fiberEventNameKey).(string)
eventName = utils.CopyString(eventName)
// Optional trail set via c.Locals(fiberTrailKey, "flow-123")
trail, _ := c.Locals(fiberTrailKey).(string)
trail = utils.CopyString(trail)
// Read everything off the Ctx HERE, never inside the goroutine:
// Fiber pools and resets the Ctx as soon as the handler returns, so a
// deferred read is a nil dereference that panics the whole process.
snap := snapshot(c)
go emit(snap, status, elapsed, bodyBytes, eventName, trail, err, cfg)
return err
}
}
type eventPayload struct {
Method string `json:"method"`
Path string `json:"path"`
Status int `json:"status"`
LatencyMs int64 `json:"latency_ms"`
ClientIP string `json:"client_ip"`
UserAgent string `json:"user_agent,omitempty"`
RequestBodyHash string `json:"request_body_hash,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
}
// Todos os valores de meta precisam ser strings (omitempty para opcionais).
// Every meta value must be a string (omitempty for optional fields).
type eventMeta struct {
Type string `json:"type"`
EventName string `json:"event_name"`
Service string `json:"service"`
Env string `json:"env"`
Environment string `json:"environment"`
RequestID string `json:"request_id"`
ImmutableTrail string `json:"immutable_trail,omitempty"`
// Chaves reservadas do contrato, todas string. client_ip: IP puro, sem porta.
// Reserved contract keys, all strings. client_ip: plain IP, no port.
ClientIP string `json:"client_ip,omitempty"`
HTTPMethod string `json:"http_method,omitempty"`
HTTPStatus string `json:"http_status,omitempty"`
HTTPRoute string `json:"http_route,omitempty"`
LogLevel string `json:"log_level,omitempty"`
ErrorType string `json:"error_type,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
}
type eventBody struct {
Payload string `json:"payload"`
Meta eventMeta `json:"meta"`
}
// reqSnapshot holds the request data copied out of the fiber.Ctx while it is
// still valid, so the background goroutine never touches the pooled Ctx.
// Every string is copied (utils.CopyString): with Immutable: false (the Fiber
// default) c.Get, c.Path, c.Method etc. return strings that point into buffers
// fasthttp reuses for the next request.
type reqSnapshot struct {
requestID string
method string
path string
route string
clientIP string
userAgent string
trailHdr string
}
func snapshot(c *fiber.Ctx) reqSnapshot {
requestID := utils.CopyString(c.Get("X-Request-Id"))
if requestID == "" {
requestID = fmt.Sprintf("%d", time.Now().UnixNano())
}
// Ordem: 1o IP do X-Forwarded-For, depois X-Real-IP, depois o IP do socket (sem porta).
// Order: first X-Forwarded-For entry, then X-Real-IP, then the socket IP (no port).
ip := clientIP(c)
// Template da rota (ex: /users/:id); cai no path concreto se nao houver
// Route template (e.g. /users/:id); falls back to the concrete path
route := c.Path()
if r := c.Route(); r != nil && r.Path != "" {
route = r.Path
}
return reqSnapshot{
requestID: requestID,
method: utils.CopyString(c.Method()),
path: utils.CopyString(c.Path()),
route: utils.CopyString(route),
clientIP: utils.CopyString(ip),
userAgent: string(c.Request().Header.UserAgent()),
trailHdr: utils.CopyString(c.Get("X-Imtbl-Trail")),
}
}
// responseStatus e o status que o cliente vai receber. Quando a cadeia retorna erro,
// o ErrorHandler do Fiber so escreve a resposta depois que este middleware retorna,
// entao c.Response().StatusCode() ainda tem o valor antigo (normalmente 200).
// Mesma regra do DefaultErrorHandler: *fiber.Error -> seu Code; outro erro -> 500.
// Um ErrorHandler customizado que escolha outro status diverge desta regra.
// responseStatus is the status the client will receive. When the chain returns an
// error, Fiber's ErrorHandler only writes the response after this middleware
// returns, so c.Response().StatusCode() still holds the old value (usually 200).
// Same rule as the DefaultErrorHandler: *fiber.Error -> its Code; any other error -> 500.
// A custom ErrorHandler that picks another status diverges from this rule.
func responseStatus(c *fiber.Ctx, err error) int {
if err == nil {
return c.Response().StatusCode()
}
var fe *fiber.Error
if errors.As(err, &fe) {
return fe.Code
}
return fiber.StatusInternalServerError
}
// clientIP returns the real client IP, honouring the proxy headers, in this
// order: the first X-Forwarded-For entry (the original client of the chain),
// then X-Real-IP, then c.IP() (the socket address, unless the Fiber app was
// created with a ProxyHeader). A candidate that is not a valid IP is skipped
// and the next one is tried. Returns "" when none is valid, and then the
// client_ip key is omitted from meta: the platform only promotes a bare IP
// (no port) to source.ip and silently drops anything else.
// The headers are only trustworthy behind a proxy/ALB that overwrites them:
// without one, any caller can forge X-Forwarded-For.
func clientIP(c *fiber.Ctx) string {
if xff := c.Get("X-Forwarded-For"); xff != "" {
if ip := bareIP(strings.SplitN(xff, ",", 2)[0]); ip != "" {
return ip
}
}
if ip := bareIP(c.Get("X-Real-IP")); ip != "" {
return ip
}
return bareIP(c.IP())
}
// bareIP trims v, strips a port ("10.0.0.1:8080", "[2001:db8::1]:8080") or
// brackets ("[2001:db8::1]") and returns the IP, or "" if v is not a valid IP.
func bareIP(v string) string {
v = strings.TrimSpace(v)
if host, _, err := net.SplitHostPort(v); err == nil {
v = host
} else if strings.HasPrefix(v, "[") && strings.HasSuffix(v, "]") {
v = v[1 : len(v)-1]
}
if net.ParseIP(v) == nil {
return ""
}
return v
}
func emit(s reqSnapshot, status int, elapsed time.Duration,
body []byte, customName string, customTrail string, handlerErr error, cfg Config) {
requestID := s.requestID
eventName := customName
if eventName == "" {
eventName = strings.ToLower(s.method) + "." +
strings.ReplaceAll(strings.TrimPrefix(s.path, "/"), "/", ".")
}
// Trilha imutavel: c.Locals(fiberTrailKey, ...) -> header X-Imtbl-Trail.
trail := sanitizeTrail(customTrail)
if trail == "" {
trail = sanitizeTrail(s.trailHdr)
}
kind := "success"
if status >= 400 || handlerErr != nil {
kind = "error"
} else if status >= 300 {
kind = "info"
}
p := eventPayload{
Method: s.method,
Path: s.path,
Status: status,
LatencyMs: elapsed.Milliseconds(),
ClientIP: s.clientIP,
UserAgent: s.userAgent,
}
if len(body) > 0 {
p.RequestBodyHash = sha256Hex(body)
}
if handlerErr != nil {
p.ErrorMessage = handlerErr.Error()
}
payloadJSON, _ := json.Marshal(p)
evt := eventBody{
Payload: string(payloadJSON),
Meta: eventMeta{
Type: kind,
EventName: eventName,
Service: cfg.ServiceName,
Env: cfg.Env,
Environment: cfg.Env,
RequestID: requestID,
ImmutableTrail: trail,
ClientIP: s.clientIP,
HTTPMethod: s.method,
HTTPStatus: strconv.Itoa(status),
HTTPRoute: s.route,
LogLevel: logLevelFrom(kind),
},
}
// Erro do handler: tipo e mensagem (max 500) em meta, como strings.
// Handler error: type and message (max 500) in meta, as strings.
if handlerErr != nil {
msg := handlerErr.Error()
if len(msg) > 500 {
msg = msg[:500]
}
evt.Meta.ErrorType = fmt.Sprintf("%T", handlerErr)
evt.Meta.ErrorMessage = msg
}
evtJSON, _ := json.Marshal(evt)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
cfg.APIURL+"/v1/events", bytes.NewBuffer(evtJSON))
if err != nil {
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+cfg.APIKey)
// Idempotency-Key e OBRIGATORIO (sem ele a API responde 400).
req.Header.Set("Idempotency-Key", requestID)
req.Header.Set("Request-Id", requestID)
req.Header.Set("X-Client-TZ", cfg.ClientTZ)
req.Header.Set("X-Client-Offset-Minutes", fmt.Sprintf("%d", cfg.ClientOffsetMinutes))
if trail != "" {
req.Header.Set("X-Imtbl-Trail", trail)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
}
// logLevelFrom mapeia o kind para meta.log_level / maps kind to meta.log_level.
func logLevelFrom(kind string) string {
if kind == "error" {
return "error"
}
return "info"
}
func sha256Hex(data []byte) string {
h := sha256.Sum256(data)
return fmt.Sprintf("%x", h)
}Registro global
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/yourorg/yourapp/immutablelog"
)
func main() {
app := fiber.New()
// Register globally - applies to all routes
app.Use(immutablelog.New(immutablelog.Config{
APIKey: "iml_live_xxxx",
ServiceName: "my-api",
Env: "production",
SkipPaths: []string{"/health", "/metrics"},
}))
app.Get("/health", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"ok": true})
})
app.Post("/payments", paymentsHandler)
app.Listen(":8080")
}Como funciona
1. c.Next() + responseStatus()
c.Next() executa toda a cadeia de handlers. Sem erro, o status é c.Response().StatusCode(). Com erro, o ErrorHandler do Fiber ainda não escreveu a resposta, então o status é derivado do erro: *fiber.Error usa o seu Code, qualquer outro erro vira 500.
2. Captura de erro por retorno
Em Go/Fiber, erros são retornados, não lançados. O middleware captura o error retornado por c.Next() e o inclui no evento se não for nil (error_type e error_message), junto com o status derivado do erro por responseStatus(): o Code de um *fiber.Error ou 500. Um ErrorHandler customizado que escolha outro status diverge dessa regra.
3. clientIP() / bareIP()
O client_ip é resolvido nesta ordem: primeiro IP do X-Forwarded-For, depois X-Real-IP, depois o IP do socket via c.IP(). Cada candidato passa por bareIP(): a porta é removida (10.0.0.1:8080, [2001:db8::1]:8080) e o valor precisa ser um IP válido. Candidato inválido é ignorado e a busca passa ao próximo. Se nenhum for válido, a chave client_ip é omitida do meta. O X-Forwarded-For só é confiável atrás de um proxy/ALB confiável que o sobrescreva: sem um, qualquer chamador o forja.
Evento customizado
Use c.Locals() para passar o nome do evento do handler para o middleware. Locals persiste durante todo o ciclo de vida da requisição.
func paymentsHandler(c *fiber.Ctx) error {
// Set custom event name via Locals - middleware reads after c.Next()
c.Locals("imtbl.eventName", "payment.created")
var req PaymentRequest
if err := c.BodyParser(&req); err != nil {
return c.Status(400).JSON(fiber.Map{"error": err.Error()})
}
// ... process payment ...
return c.Status(201).JSON(fiber.Map{"ok": true, "payment_id": "pay_123"})
}Trilha imutável (immutable_trail)
A trilha agrupa eventos relacionados em uma mesma linha do tempo auditável. Defina via c.Locals("imtbl.trail", ...) no handler ou propague entre serviços com o header X-Imtbl-Trail.
func runFlowHandler(c *fiber.Ctx) error {
c.Locals("imtbl.trail", "flow-"+c.Params("id"))
// ... business logic ...
return c.JSON(fiber.Map{"ok": true})
}A trilha não pode ser vazia, exceder 256 caracteres ou conter ":", violações retornam 400 invalid_immutable_trail. O sanitizeTrail corrige o valor antes do envio.
Body recycling
O Fiber (fasthttp) reutiliza buffers de request/response para alta performance. É necessário copiar o body antes de c.Next() para garantir que o hash seja calculado sobre os dados corretos.
// Fiber (fasthttp) recycles request buffers for high performance.
// Always copy the body BEFORE calling c.Next():
bodyBytes := make([]byte, len(c.Body()))
copy(bodyBytes, c.Body())
err := c.Next()
// After this, c.Body() may be empty or contain data from another request.
// Use bodyBytes for hashing - it has a stable copy.ErrorHandler
O ErrorHandler global do Fiber processa erros retornados pelos handlers. O middleware de audit captura o erro ANTES do ErrorHandler, então o status do evento é derivado do erro por responseStatus() (Code do *fiber.Error, ou 500) e error_type e error_message ficam no evento de auditoria.
// Fiber's global ErrorHandler processes errors returned by handlers.
// The audit middleware captures the error returned from c.Next()
// BEFORE ErrorHandler runs - it's included in the event as error_message.
app := fiber.New(fiber.Config{
ErrorHandler: func(c *fiber.Ctx, err error) error {
code := fiber.StatusInternalServerError
if e, ok := err.(*fiber.Error); ok {
code = e.Code
}
return c.Status(code).JSON(fiber.Map{"error": err.Error()})
},
})
// Handler that returns an error:
app.Get("/fail", func(c *fiber.Ctx) error {
return fiber.NewError(500, "something went wrong")
// audit middleware captures: http_status="500", error_type, error_message="something went wrong"
})Campos de meta
Além do payload, o objeto meta carrega os campos que o SIEM usa para normalizar (ECS) e enriquecer o evento. Todos os valores de meta são strings.
| Campo em meta | O que faz no SIEM |
|---|---|
event_name | O rótulo do evento (ex.: http.GET.auth-me-user, Pagamento erro), o identificador que aparece na listagem. Vira event.action e deriva event.category (ex.: nome com login → authentication). |
client_ip | Vira source.ip com precedência máxima e proveniência client_asserted. É o único campo de meta que vira source.ip. Deve ser IP puro, sem porta. Ver a seção abaixo. |
immutable_trail | Vira imtbl.immutable_trail, que agrupa eventos relacionados para investigação (ex.: um pedido, um usuário). |
type | Severidade do evento: error / warning / info / success. Colore o badge na listagem. (event_type é aceito como sinônimo.) |
http_method, http_status, http_route, log_level, environment, error_type, error_message | Enviados pelos middlewares, sempre como string (inclusive http_status, ex.: "200"). error_type e error_message só existem quando há erro. |
service, env, request_id | Metadados: indexados e consultáveis no painel (busca/filtros). |
client_ip: IP do usuário final
O problema que resolve
Entre o navegador e o core há proxies/ALB. O IP que o core observa na conexão é o do salto anterior (o backend do cliente ou um proxy da AWS), não o do usuário. Sem ação, source.ip seria o IP do proxy, inútil para geo, threat e detecção por IP. (Exemplo real: o XFF chegava 44.192.13.3 (AWS) enquanto o usuário era 179.110.4.205.)
A solução
O backend do cliente é o único que enxerga o IP real do navegador, então ele encaminha esse IP em meta.client_ip ao chamar POST /v1/events.
Como o SIEM trata
- Valida que é um IP (v4/v6). Um valor que não seja IP é ignorado, sem derrubar o evento. Um IP com porta (ex.:
1.2.3.4:5678) também é descartado em silêncio. - Escreve em
source.ipcom precedência máxima (ver ordem abaixo). - Carimba
imtbl.source_ip_origin = "client_asserted"; a UI mostra o selo “IP do usuário”. - Alimenta GeoIP, threat intel e regras de detecção por IP.
client_ipX-Forwarded-For (1º hop)X-Real-IPIP de conexãoProveniência e confiança
client_ip é asserido pelo tenant: o backend do cliente afirma o IP, e o valor é falsificável por quem controla aquele backend. Porém ele fica contido no próprio tenant (não cruza a fronteira de outro tenant). Um hit de threat/geo sobre um client_asserted é uma alegação, não uma observação de borda.
Como obter o IP no seu backend
Teste os candidatos na ordem: o primeiro IP do X-Forwarded-For (o mais próximo do usuário), depois o X-Real-IP (se o seu proxy o define) e por fim o IP de conexão. Cada candidato passa por uma função que remove a porta (1.2.3.4:5678, [2001:db8::1]:8080) e os colchetes e valida que é um IP de verdade, sem consultar DNS. Um valor inválido (lixo, localhost, zona IPv6 como fe80::1%eth0) é ignorado e o próximo candidato é tentado. Envie IP puro, sem porta, e se nenhum candidato for um IP válido omita a chave client_ip (meta não aceita null, e nunca envie “unknown”).
Só atrás de proxy confiável: ler o primeiro IP do X-Forwarded-For só é seguro quando há um proxy ou ALB confiável na frente da aplicação, que sobrescreve ou acrescenta o header. Sem proxy, o cliente controla o header e pode forjar o IP, e o SIEM promoverá esse valor a source.ip.
O código de getClientIp (clientIP, get_client_ip) do middleware desta página implementa essa regra, na ordem de candidatos que ele mostra.
Exemplo de payload
{
"payload": "{\"user\":\"bob\",\"action\":\"login\"}",
"meta": {
"event_name": "user.login",
"client_ip": "179.110.4.205",
"immutable_trail": "user-bob"
}
}Nota de PII: client_ip é PII e vai selado no bloco imutável (permanente). Decida conscientemente entre evidência forense e “direito ao esquecimento” antes de enviá-lo.
Esta documentação reflete o comportamento atual da integração. Para dúvidas ou integrações avançadas, entre em contato com o time de suporte.
