Pular para o conteúdo principal
ImmutableLog logo
← Voltar
AxumRust

Integração com Axum

Integre o ImmutableLog em qualquer aplicação Axum com um middleware `from_fn_with_state` que captura as requisições HTTP (exceto OPTIONS e os paths de `skip_paths`). O envio roda num `tokio::spawn`: a resposta não espera o ImmutableLog, e uma falha de envio só gera um `tracing::warn!`.

Dependências

O middleware não é um crate publicado: você copia o arquivo para o seu projeto. Adicione ao `Cargo.toml` da sua aplicação apenas as dependências de terceiros que ele usa. O envio usa `reqwest` com timeout de 5 s.

toml
[dependencies]
axum = "0.8"            # ou "0.7"
tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.12", features = ["json"] }
serde_json = "1"
uuid = { version = "1", features = ["v4"] }
tracing = "0.1"

O `reqwest` padrão usa a TLS nativa do sistema (OpenSSL no Linux). Para não depender dela: reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }

Código do middleware

Copie o arquivo `middleware.rs` do GitHub para `src/immutablelog.rs` e declare `mod immutablelog;`. O middleware copia da requisição tudo o que o evento precisa antes de `next.run(req)`, lê o status na resposta e envia o evento em uma task separada. Handler que entra em panic também gera evento.

rust
//! ImmutableLog middleware for Axum (0.7 / 0.8), written as a `from_fn_with_state` function.
//!
//! Copy this file into your crate (e.g. `src/immutablelog.rs`) and register it with
//! `.layer(middleware::from_fn_with_state(cfg.clone(), immutablelog::audit))`.
//! Dependencies are listed in the README; this file has no manifest of its own.

use std::any::Any;
use std::collections::HashMap;
use std::future::Future;
use std::net::{IpAddr, SocketAddr};
use std::panic::{self, AssertUnwindSafe};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use axum::{
    extract::{ConnectInfo, MatchedPath, Request, State},
    http::Method,
    middleware::Next,
    response::Response,
};
use serde_json::json;
use uuid::Uuid;

const DEFAULT_API_URL: &str = "https://api.immutablelog.com";
const MAX_ERROR_MESSAGE: usize = 500;
const MAX_PATH: usize = 2048;
const MAX_USER_AGENT: usize = 512;
const MAX_TRAIL: usize = 256;

/// Middleware configuration. Build it with [`Config::from_env`], adjust, wrap in `Arc`.
#[derive(Clone)]
pub struct Config {
    pub api_key: String,
    pub api_url: String,
    pub service: String,
    pub env: String,
    /// Exact paths that never generate an event.
    pub skip_paths: Vec<String>,
    /// Read `X-Imtbl-Trail` from the incoming request when the handler sets no `Trail`.
    /// Off by default: the header is controlled by whoever calls the service.
    pub trust_trail_header: bool,
    pub http: reqwest::Client,
}

impl Config {
    /// Reads `IMTBL_API_KEY`, `IMTBL_URL`, `IMTBL_SERVICE_NAME` and `IMTBL_ENV`.
    /// `service` is used when `IMTBL_SERVICE_NAME` is not set.
    pub fn from_env(service: &str) -> Self {
        let var = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty());
        let api_key = var("IMTBL_API_KEY").unwrap_or_default();
        if api_key.is_empty() {
            tracing::warn!("[ImmutableLog] IMTBL_API_KEY is empty: no event will be sent");
        }
        Self {
            api_key,
            api_url: var("IMTBL_URL").unwrap_or_else(|| DEFAULT_API_URL.to_string()),
            service: var("IMTBL_SERVICE_NAME").unwrap_or_else(|| service.to_string()),
            env: var("IMTBL_ENV").unwrap_or_else(|| "production".to_string()),
            skip_paths: vec!["/health".into(), "/healthz".into()],
            trust_trail_header: false,
            http: reqwest::Client::builder()
                .timeout(Duration::from_secs(5))
                .build()
                .expect("build reqwest client"),
        }
    }
}

/// Custom event name. A handler puts it in the *response* extensions
/// (`res.extensions_mut().insert(..)` or `(Extension(EventName(..)), body)`).
#[derive(Clone)]
pub struct EventName(pub String);

/// Immutable trail (`meta.immutable_trail`), also carried in the response extensions.
#[derive(Clone)]
pub struct Trail(pub String);

/// Error detail for `meta.error_type` / `meta.error_message`. Axum turns errors into
/// responses before the middleware sees them, so the app's `IntoResponse` for its error
/// type inserts this in the response extensions (see the README).
#[derive(Clone)]
pub struct ErrorInfo {
    pub error_type: String,
    pub message: String,
}

impl ErrorInfo {
    /// `error_type` is the Rust type name of `E`, `message` is its `Display`.
    pub fn from_error<E: std::fmt::Display>(err: &E) -> Self {
        Self { error_type: std::any::type_name::<E>().to_string(), message: err.to_string() }
    }
}

/// Everything the event needs from the request, copied before `next.run`.
/// The spawned task never touches the request (copy, then spawn).
struct RequestFacts {
    started: Instant,
    method: String,
    path: String,
    route: Option<String>,
    user_agent: String,
    client_ip: Option<String>,
    header_trail: Option<String>,
}

/// The middleware. Register with `middleware::from_fn_with_state(cfg, audit)`.
pub async fn audit(State(cfg): State<Arc<Config>>, req: Request, next: Next) -> Response {
    let path = req.uri().path().to_string();
    // Preflight and skipped paths never generate an event.
    if req.method() == Method::OPTIONS || cfg.skip_paths.iter().any(|p| *p == path) {
        return next.run(req).await;
    }

    // Built in its own scope: a `&Request` held across the `.await` below would make the
    // future !Send (the body is not Sync) and the layer would not compile.
    let facts = {
        let header = |name: &str| {
            req.headers().get(name).and_then(|v| v.to_str().ok()).map(str::to_string)
        };
        RequestFacts {
            started: Instant::now(),
            method: req.method().as_str().to_string(),
            // MatchedPath is the route template ("/users/{id}"). It exists when the middleware
            // is added with Router::layer and a route matched; absent on the fallback (404).
            route: req.extensions().get::<MatchedPath>().map(|m| m.as_str().to_string()),
            user_agent: header("user-agent").unwrap_or_default(),
            // The socket peer is only known when the app is served with
            // `into_make_service_with_connect_info::<SocketAddr>()`.
            client_ip: client_ip(
                header("x-forwarded-for").as_deref(),
                header("x-real-ip").as_deref(),
                req.extensions().get::<ConnectInfo<SocketAddr>>().map(|c| c.0.ip()),
            ),
            header_trail: if cfg.trust_trail_header { header("x-imtbl-trail") } else { None },
            path,
        }
    };

    match CatchUnwind::new(next.run(req)).await {
        Ok(res) => {
            let status = res.status().as_u16();
            let exts = res.extensions();
            let event_name = exts.get::<EventName>().map(|e| e.0.clone());
            let trail = exts.get::<Trail>().map(|t| t.0.clone());
            let error = exts.get::<ErrorInfo>().map(|e| (e.error_type.clone(), e.message.clone()));
            dispatch(cfg, facts, status, event_name, trail, error);
            res
        }
        Err(p) => {
            // Send the event as a 500 and re-panic: whatever the app does with a panic
            // (CatchPanicLayer, or hyper dropping the connection) stays the same.
            let message = panic_message(&p);
            dispatch(cfg, facts, 500, None, None, Some(("panic".into(), message)));
            panic::resume_unwind(p)
        }
    }
}

/// Builds the event from owned values and spawns the send. Never blocks the response.
fn dispatch(
    cfg: Arc<Config>,
    facts: RequestFacts,
    status: u16,
    event_name: Option<String>,
    trail: Option<String>,
    error: Option<(String, String)>,
) {
    if cfg.api_key.is_empty() {
        return;
    }
    let latency_ms = facts.started.elapsed().as_millis() as u64;
    let kind = kind_from(status);
    let request_id = Uuid::new_v4().to_string();
    let path = truncate(&facts.path, MAX_PATH);
    let event_name = event_name.unwrap_or_else(|| format!("http.{}.{}", facts.method, path));
    let route = facts.route.clone().filter(|r| !r.is_empty()).unwrap_or_else(|| path.clone());
    let trail = trail.or(facts.header_trail).and_then(|t| sanitize_trail(&t));

    let mut payload = json!({
        "id": Uuid::new_v4().to_string(),
        "kind": kind,
        "message": format!("{} {} -> {}", facts.method, path, status),
        "timestamp_ms": SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0),
        "context": {
            "ip": facts.client_ip.clone().unwrap_or_else(|| "unknown".into()),
            "user_agent": truncate(&facts.user_agent, MAX_USER_AGENT),
        },
        "request": { "request_id": request_id, "method": facts.method.clone(), "path": path.clone() },
        "metrics": { "latency_ms": latency_ms, "status_code": status },
        "severity": if kind == "error" { "high" } else { "low" },
    });
    if kind == "error" {
        payload["error"] = json!({
            "status_code": status,
            "retryable": matches!(status, 408 | 429 | 500 | 502 | 503 | 504),
        });
        if let Some((t, m)) = &error {
            payload["error"]["exception"] = json!(t);
            payload["error"]["exception_message"] = json!(truncate(m, MAX_ERROR_MESSAGE));
        }
    }

    // meta is a string -> string map in the core: every value here is a String.
    let mut meta: HashMap<String, String> = HashMap::new();
    meta.insert("type".into(), kind.into());
    meta.insert("event_type".into(), kind.into());
    meta.insert("event_name".into(), event_name);
    meta.insert("service".into(), cfg.service.clone());
    meta.insert("request_id".into(), request_id.clone());
    // "env" is the legacy key; "environment" is the canonical one (CONTRACT.md §4.1).
    meta.insert("env".into(), cfg.env.clone());
    meta.insert("environment".into(), cfg.env.clone());
    meta.insert("http_method".into(), facts.method.clone());
    meta.insert("http_status".into(), status.to_string());
    meta.insert("http_route".into(), route);
    meta.insert("log_level".into(), log_level_from(kind).into());
    if let Some(ip) = facts.client_ip {
        meta.insert("client_ip".into(), ip);
    }
    if let Some((t, m)) = error {
        meta.insert("error_type".into(), t);
        if !m.is_empty() {
            meta.insert("error_message".into(), truncate(&m, MAX_ERROR_MESSAGE));
        }
    }
    if let Some(t) = trail {
        meta.insert("immutable_trail".into(), t);
    }

    let body = json!({ "payload": payload.to_string(), "meta": meta });
    tokio::spawn(async move {
        let sent = cfg
            .http
            .post(format!("{}/v1/events", cfg.api_url.trim_end_matches('/')))
            .bearer_auth(&cfg.api_key)
            .header("Idempotency-Key", &request_id)
            .json(&body)
            .send()
            .await;
        match sent {
            Ok(r) if r.status().is_success() => {}
            Ok(r) => tracing::warn!("[ImmutableLog] event rejected: HTTP {}", r.status().as_u16()),
            Err(e) => tracing::warn!("[ImmutableLog] failed to send event: {e}"),
        }
    });
}

/// `client_ip` for the SIEM: first entry of `X-Forwarded-For`, then `X-Real-IP`, then the
/// socket peer. Only a bare IP is returned (no port): the SIEM drops `ip:port` silently.
/// Headers are trusted as they come; see "Proxy e X-Forwarded-For" in the README.
fn client_ip(xff: Option<&str>, real_ip: Option<&str>, peer: Option<IpAddr>) -> Option<String> {
    let from_headers = xff
        .and_then(|v| v.split(',').next())
        .and_then(bare_ip)
        .or_else(|| real_ip.and_then(bare_ip));
    from_headers.or_else(|| peer.map(|ip| canonical(ip).to_string()))
}

/// "203.0.113.7", "203.0.113.7:4711", "[2001:db8::1]:8080" and "2001:db8::1" -> bare IP.
fn bare_ip(raw: &str) -> Option<String> {
    let s = raw.trim();
    let host = if let Some(rest) = s.strip_prefix('[') {
        rest.split(']').next().unwrap_or("")
    } else if s.matches(':').count() == 1 {
        s.split(':').next().unwrap_or("")
    } else {
        s
    };
    host.parse::<IpAddr>().ok().map(|ip| canonical(ip).to_string())
}

/// "::ffff:10.0.0.1" -> "10.0.0.1".
fn canonical(ip: IpAddr) -> IpAddr {
    match ip {
        IpAddr::V6(v6) => v6.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(ip),
        v4 => v4,
    }
}

/// The core rejects a trail that is empty, longer than 256 chars or contains ':'.
fn sanitize_trail(v: &str) -> Option<String> {
    let s: String = v.trim().replace(':', "-").chars().take(MAX_TRAIL).collect();
    if s.is_empty() { None } else { Some(s) }
}

fn kind_from(status: u16) -> &'static str {
    match status {
        400.. => "error",
        300..=399 => "info",
        200..=299 => "success",
        _ => "info",
    }
}

/// Middleware kind -> `meta.log_level` (ECS log.level). Same table as the other middlewares.
fn log_level_from(kind: &str) -> &'static str {
    match kind {
        "error" => "error",
        "warning" => "warn",
        "debug" => "debug",
        _ => "info",
    }
}

fn panic_message(p: &Box<dyn Any + Send>) -> String {
    p.downcast_ref::<&str>()
        .map(|s| s.to_string())
        .or_else(|| p.downcast_ref::<String>().cloned())
        .unwrap_or_else(|| "panic".into())
}

fn truncate(s: &str, max: usize) -> String {
    s.chars().take(max).collect()
}

/// Polls the inner future inside `catch_unwind`, so a panicking handler still produces
/// an event. The panic is re-raised by the caller.
struct CatchUnwind<F> {
    inner: Pin<Box<F>>,
}

impl<F> CatchUnwind<F> {
    fn new(f: F) -> Self {
        Self { inner: Box::pin(f) }
    }
}

impl<F: Future> Future for CatchUnwind<F> {
    type Output = Result<F::Output, Box<dyn Any + Send>>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let inner = self.get_mut().inner.as_mut();
        match panic::catch_unwind(AssertUnwindSafe(|| inner.poll(cx))) {
            Ok(Poll::Pending) => Poll::Pending,
            Ok(Poll::Ready(v)) => Poll::Ready(Ok(v)),
            Err(p) => Poll::Ready(Err(p)),
        }
    }
}

Registro e Configuração

Registre o middleware com `from_fn_with_state` aplicando o `Config` compartilhado via `Arc`. Use `Router::layer` (não `route_layer`) para que o 404 do fallback também gere evento, e `into_make_service_with_connect_info::<SocketAddr>()` para o middleware conhecer o IP do socket.

rust
use std::{net::SocketAddr, sync::Arc};
use axum::{middleware, routing::{get, post}, Router};

mod immutablelog;
use immutablelog::{audit, Config};

#[tokio::main]
async fn main() {
    let mut cfg = Config::from_env("my-axum-service");
    cfg.skip_paths.push("/metrics".into());
    let cfg = Arc::new(cfg);

    let app = Router::new()
        .route("/users/{id}", get(get_user))      // axum 0.7: "/users/:id"
        .route("/payments", post(payments))
        // Router::layer (não route_layer): assim o 404 do fallback também gera evento.
        .layer(middleware::from_fn_with_state(cfg.clone(), audit));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    // with_connect_info: sem isso o middleware não conhece o IP do socket (ver client_ip).
    axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>())
        .await
        .unwrap();
}

O `Config::from_env(service)` lê as variáveis abaixo. Antes do `Arc::new` você pode ajustar os campos `api_key`, `api_url`, `service`, `env`, `skip_paths` (comparação exata; padrão `/health` e `/healthz`), `trust_trail_header` e `http` (o `reqwest::Client`, com timeout de 5 s).

VariávelObrigatóriaDescrição
IMTBL_API_KEYSimChave de API do ImmutableLog, com scope `events:write`
IMTBL_URLNãoURL base da API (padrão `https://api.immutablelog.com`)
IMTBL_SERVICE_NAMENãoNome do serviço (`meta.service`); padrão: o argumento de `from_env`
IMTBL_ENVNãoAmbiente (`meta.environment` e `meta.env`); padrão `production`

Sem `IMTBL_API_KEY`, o middleware registra um aviso ao montar o `Config` e não envia nada.

Nunca coloque IMTBL_API_KEY no código. Use variável de ambiente ou um secrets manager.

Como funciona

antes de next.run

Copia método, path, MatchedPath, User-Agent, client_ip e, se ligado, o header de trilha

next.run(req).await

Executa a cadeia; o status sai na Response

tokio::spawn

Evento enviado em task separada: a resposta não espera

Idempotency-Key

Um UUID v4 novo por evento, igual a meta.request_id. O X-Request-Id recebido não é usado, porque vem do chamador e dois eventos diferentes com o mesmo valor seriam descartados como duplicata

body

O middleware nunca lê o body da requisição: nem conteúdo, nem hash

Evento e trilha customizados

No Axum o handler não tem mais acesso à requisição depois de consumi-la, então os marcadores `EventName` e `Trail` vão nas extensions da resposta. O middleware lê esses marcadores depois de `next.run`.

rust
use axum::{http::StatusCode, response::IntoResponse, Extension, Json};
use crate::immutablelog::{EventName, Trail};

async fn payments() -> impl IntoResponse {
    (
        StatusCode::CREATED,
        Extension(EventName("payment.created".into())),
        Extension(Trail("order-7782".into())),
        Json(serde_json::json!({ "ok": true })),
    )
}

Erros: o Axum transforma o erro em resposta antes de o middleware ver, então `error_type` e `error_message` só aparecem se o `IntoResponse` do seu tipo de erro anexar um `ErrorInfo` (`ErrorInfo::from_error`). Uma resposta 5xx sem `ErrorInfo` gera evento com `type: error`, mas sem `error_*`.

rust
use axum::response::{IntoResponse, Response};
use crate::immutablelog::ErrorInfo;

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let mut res = (StatusCode::INTERNAL_SERVER_ERROR, "internal error").into_response();
        // error_type = nome do tipo Rust (std::any::type_name), error_message = Display
        res.extensions_mut().insert(ErrorInfo::from_error(&self));
        res
    }
}

Padrão automático: http.METHOD.path.

Trilha imutável (immutable_trail)

A trilha agrupa eventos relacionados em uma mesma linha do tempo auditável e vai em `meta.immutable_trail`. Anexe `Trail(...)` na resposta de um handler. O valor passa por `sanitize_trail` antes do envio.

rust
async fn run_flow(/* ... */) -> Response {
    let mut res = Json(json!({ "status": "ok" })).into_response();
    res.extensions_mut().insert(Trail("flow-123".into()));
    res
}

A trilha não pode ser vazia, exceder 256 caracteres ou conter `:`, e violações retornam `400 invalid_immutable_trail`. Por isso o `sanitize_trail` troca `:` por `-`, corta em 256 e omite a chave se sobrar vazio.

O header `X-Imtbl-Trail` é opcional e fica desligado por padrão. Só é lido com `cfg.trust_trail_header = true` e só quando o handler não definiu `Trail`. O header vem de quem chama o serviço, então qualquer chamador poderia pendurar eventos numa trilha alheia do mesmo tenant. Ligue só quando o serviço recebe chamadas apenas de serviços internos seus.

Resposta e códigos de status

A API de ingestão é assíncrona. Sucesso retorna 202 (novo) ou 200 (duplicata idempotente). O middleware não espera essa resposta (uma recusa só gera um `tracing::warn!`), então esses códigos importam principalmente se você enviar eventos manualmente.

StatusSignificado
202Evento aceito e enfileirado (novo)
200Idempotency-Key já existente (duplicate: true)
400Idempotency-Key ausente/vazia ou invalid_immutable_trail
403Assinatura inativa/expirada, escopo ou retenção
413payload_too_large (limite do servidor: 16KB)
429monthly_limit_exceeded, não fazer retry
503mempool_full, transitório, pode dar retry

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 metaO que faz no SIEM
event_nameO 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_ipVira 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_trailVira imtbl.immutable_trail, que agrupa eventos relacionados para investigação (ex.: um pedido, um usuário).
typeSeveridade 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_messageEnviados pelos middlewares, sempre como string (inclusive http_status, ex.: "200"). error_type e error_message só existem quando há erro.
service, env, request_idMetadados: 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.ip com 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.
Precedência de source.ip:client_ipX-Forwarded-For (1º hop)X-Real-IPIP de conexão

Proveniê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.

rust
use serde_json::json;
use std::net::{IpAddr, SocketAddr};
use std::str::FromStr;

fn bare_ip(value: &str) -> Option<String> {
    let mut v = value.trim();
    if let Some(inner) = v.strip_prefix('[') {
        let end = inner.find(']')?;
        let rest = &inner[end + 1..];
        let port_ok = rest.len() > 1 && rest.starts_with(':') && rest[1..].bytes().all(|b| b.is_ascii_digit());
        if !(rest.is_empty() || port_ok) {
            return None;
        }
        v = &inner[..end];
    } else if v.matches(':').count() == 1 {
        v = v.split(':').next()?; // 1.2.3.4:5678 -> 1.2.3.4
    }
    if v.contains('%') {
        return None; // zona IPv6 (fe80::1%eth0) nao e IP puro
    }
    IpAddr::from_str(v).ok().map(|_| v.to_string()) // nao consulta DNS
}

// Agnostico (actix/axum): passe os valores crus. Candidatos na ordem:
// 1o item do X-Forwarded-For, X-Real-IP, IP de conexao (peer).
fn client_ip(xff: Option<&str>, xri: Option<&str>, peer: Option<SocketAddr>) -> Option<String> {
    xff.and_then(|s| bare_ip(s.split(',').next()?))
        .or_else(|| xri.and_then(bare_ip))
        .or_else(|| peer.map(|a| a.ip().to_string()))
}

fn build_meta(xff: Option<&str>, xri: Option<&str>, peer: Option<SocketAddr>) -> serde_json::Value {
    let mut meta = json!({ "event_name": "user.login" });
    if let Some(ip) = client_ip(xff, xri, peer) {
        meta["client_ip"] = json!(ip); // sem IP valido, omita a chave (nunca "unknown")
    }
    meta
}

Exemplo de payload

json
{
  "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.

Voltar para Rust