Skip to main content
ImmutableLog logo

Rust

Complete integration guide for ImmutableLog in Rust. Automatic middleware for Axum and Actix, or a direct reqwest HTTP client for workers, queue consumers, and jobs. Sending runs in a fire-and-forget tokio::spawn, adding no latency to the response.

Direct HTTP client

Use the Client to send events directly to ImmutableLog without depending on a web framework. Ideal for workers, queue consumers, cron jobs, and any async Rust code that needs to record events. The API key must have the events:write scope.

rust
// Cargo.toml:
// reqwest = { version = "0.12", features = ["json"] }
// tokio = { version = "1", features = ["full"] }
// serde_json = "1"
// uuid = { version = "1", features = ["v4"] }

use std::collections::HashMap;
use std::time::Duration;

use serde_json::json;
use uuid::Uuid;

pub struct Client {
    api_key: String,
    api_url: String,
    service: String,
    env: String,
    http: reqwest::Client,
}

impl Client {
    pub fn new(api_key: impl Into<String>, service: impl Into<String>, env: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
            api_url: "https://api.immutablelog.com".to_string(),
            service: service.into(),
            env: env.into(),
            http: reqwest::Client::builder()
                .timeout(Duration::from_secs(5))
                .build()
                .expect("build http client"),
        }
    }

    pub async fn send_event(
        &self,
        event_name: &str,
        kind: &str,                 // "success" | "info" | "error"
        payload: serde_json::Value,
        trail: Option<&str>,
    ) -> Result<(), reqwest::Error> {
        let request_id = Uuid::new_v4().to_string();
        let trail = trail.and_then(sanitize_trail);

        // Todos os valores de meta precisam ser strings.
        let mut meta: HashMap<&str, String> = HashMap::new();
        meta.insert("type", kind.to_string());
        meta.insert("event_name", event_name.to_string());
        meta.insert("service", self.service.clone());
        meta.insert("request_id", request_id.clone());
        meta.insert("env", self.env.clone());
        if let Some(t) = &trail {
            meta.insert("immutable_trail", t.clone());
        }

        let event = json!({ "payload": payload.to_string(), "meta": meta });

        let mut req = self
            .http
            .post(format!("{}/v1/events", self.api_url))
            .bearer_auth(&self.api_key)
            .header("Content-Type", "application/json")
            // Idempotency-Key e OBRIGATORIO (sem ele a API responde 400).
            .header("Idempotency-Key", format!("{}-{}", event_name, request_id))
            .header("Request-Id", &request_id)
            .header("X-Client-TZ", "America/Sao_Paulo")
            .header("X-Client-Offset-Minutes", "-180");
        if let Some(t) = &trail {
            req = req.header("X-Imtbl-Trail", t);
        }

        req.json(&event).send().await?;
        Ok(())
    }
}

// Normaliza o immutable_trail (trim, nao-vazio, max 256, sem ':').
// O servidor responde 400 invalid_immutable_trail se a regra for violada.
pub fn sanitize_trail(v: &str) -> Option<String> {
    let mut s = v.trim().replace(':', "-");
    if s.is_empty() {
        return None;
    }
    if s.chars().count() > 256 {
        s = s.chars().take(256).collect();
    }
    Some(s)
}

// Uso (fire-and-forget via tokio::spawn):
// let client = Arc::new(Client::new(std::env::var("IMTBL_API_KEY")?, "my-service", "production"));
// let c = client.clone();
// tokio::spawn(async move {
//     let _ = c.send_event("user.created", "success",
//         json!({ "user_id": "usr_123", "plan": "pro" }), Some("order-7782")).await;
// });

Wrap the Client in an Arc to share it across tasks. send_event respects the reqwest::Client 5s timeout; use tokio::spawn to fire without awaiting.

Retry with exponential backoff

For high-availability production, add retry with exponential backoff. ImmutableLog returns 202 on success and 200 on an idempotent duplicate. Never retry on 429 (monthly limit reached).

rust
// Retry em erros transitorios (nunca em 429).
// Retries transient errors (never on 429).
impl Client {
    pub async fn send_with_retry(
        &self,
        event_name: &str,
        kind: &str,
        payload: serde_json::Value,
        trail: Option<&str>,
        max_attempts: u32,
    ) -> Result<(), reqwest::Error> {
        let mut delay = Duration::from_millis(500);
        let mut last_err = None;

        for attempt in 0..max_attempts {
            match self.send_event(event_name, kind, payload.clone(), trail).await {
                Ok(()) => return Ok(()),
                Err(e) => {
                    // 429 = limite mensal - nao fazer retry.
                    if e.status().map(|s| s.as_u16()) == Some(429) {
                        return Err(e);
                    }
                    last_err = Some(e);
                    if attempt + 1 < max_attempts {
                        tokio::time::sleep(delay).await;
                        delay *= 2; // 500ms -> 1s -> 2s
                    }
                }
            }
        }
        Err(last_err.expect("at least one attempt"))
    }
}

Sensitive data hashing

Never send raw personal data (email, CPF, IP) to ImmutableLog. Use SHA-256 to generate a deterministic digest, traceable without exposing the original data.

rust
// Cargo.toml: sha2 = "0.10", hex = "0.4"
use sha2::{Digest, Sha256};

// Faz o hash de dados sensiveis antes de enviar - nunca logue PII bruto.
fn sha256_hex(data: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(data);
    hex::encode(hasher.finalize())
}

// Uso no payload do evento:
let payload = serde_json::json!({
    "user_id":    "usr_123",
    "email_hash": sha256_hex(b"user@example.com"),
    "ip_hash":    sha256_hex(b"192.168.1.1"),
});

meta fields

Beyond the payload, the meta object carries the fields the SIEM uses to normalize (ECS) and enrich the event. All meta values are strings.

Field in metaWhat it does in the SIEM
event_nameThe event label (e.g. http.GET.auth-me-user, Payment error), the identifier shown in the listing. Becomes event.action and derives event.category (e.g. a name with login → authentication).
client_ipBecomes source.ip with maximum precedence and provenance client_asserted. It is the only meta field that becomes source.ip. It must be a plain IP, without a port. See the section below.
immutable_trailBecomes imtbl.immutable_trail, which groups related events for investigation (e.g. one order, one user).
typeEvent severity: error / warning / info / success. Colors the badge in the listing. (event_type is accepted as a synonym.)
http_method, http_status, http_route, log_level, environment, error_type, error_messageSent by the middlewares, always as a string (including http_status, e.g. "200"). error_type and error_message only exist when there is an error.
service, env, request_idMetadata: indexed and queryable in the dashboard (search/filters).

client_ip: end-user IP

The problem it solves

Between the browser and the core there are proxies/ALB. The IP the core sees on the connection is the previous hop (the client's backend or an AWS proxy), not the user's. Without action, source.ip would be the proxy IP, useless for geo, threat and IP-based detection. (Real example: XFF arrived as 44.192.13.3 (AWS) while the user was 179.110.4.205.)

The solution

The client's backend is the only one that sees the browser's real IP, so it forwards that IP in meta.client_ip when calling POST /v1/events.

How the SIEM handles it

  • Validates it is an IP (v4/v6). A non-IP value is ignored, without dropping the event. An IP with a port (e.g. 1.2.3.4:5678) is also silently discarded.
  • Writes to source.ip with maximum precedence (see order below).
  • Stamps imtbl.source_ip_origin = "client_asserted"; the UI shows the “User IP” badge.
  • Feeds GeoIP, threat intel and IP-based detection rules.
source.ip precedence:client_ipX-Forwarded-For (1º hop)X-Real-IPconnection IP

Provenance and trust

client_ip is asserted by the tenant: the client's backend claims the IP, and it can be forged by whoever controls that backend. However it stays contained within the tenant (it never crosses another tenant's boundary). A threat/geo hit on a client_asserted value is a claim, not an edge observation.

How to obtain the IP in your backend

Try the candidates in order: the first IP from X-Forwarded-For (closest to the user), then X-Real-IP (if your proxy sets it) and finally the connection IP. Each candidate goes through a function that strips the port (1.2.3.4:5678, [2001:db8::1]:8080) and the brackets and checks that it is a real IP, without any DNS lookup. An invalid value (garbage, localhost, an IPv6 zone such as fe80::1%eth0) is ignored and the next candidate is tried. Send a plain IP, without a port, and if no candidate is a valid IP omit the client_ip key (meta does not accept null, and never send “unknown”).

Only behind a trusted proxy: reading the first IP from X-Forwarded-For is only safe when a trusted proxy or ALB sits in front of the application and overwrites or appends the header. Without a proxy, the client controls the header and can forge the IP, and the SIEM will promote that value to 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
}

Payload example

json
{
  "payload": "{\"user\":\"bob\",\"action\":\"login\"}",
  "meta": {
    "event_name": "user.login",
    "client_ip": "179.110.4.205",
    "immutable_trail": "user-bob"
  }
}

PII note: client_ip is PII and gets sealed into the immutable block (permanent). Decide consciously between forensic evidence and “right to be forgotten” before sending it.

This documentation reflects the current API behavior. For questions or advanced integrations, contact the support team.

Back to docs