Axum Integration
Integrate ImmutableLog into any Axum application with a `from_fn_with_state` middleware that captures HTTP requests (except OPTIONS and the `skip_paths` entries). Sending runs in a `tokio::spawn`: the response does not wait for ImmutableLog, and a send failure only produces a `tracing::warn!`.
Dependencies
The middleware is not a published crate: you copy the file into your project. Add to your application's `Cargo.toml` only the third-party dependencies it uses. Sending uses `reqwest` with a 5 s timeout.
[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"The default `reqwest` uses the system native TLS (OpenSSL on Linux). To avoid it: reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
Middleware code
Copy the `middleware.rs` file from GitHub to `src/immutablelog.rs` and declare `mod immutablelog;`. The middleware copies everything the event needs from the request before `next.run(req)`, reads the status on the response, and sends the event in a separate task. A handler that panics also produces an event.
//! 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)),
}
}
}Registration and Configuration
Register the middleware with `from_fn_with_state`, passing the shared `Config` via `Arc`. Use `Router::layer` (not `route_layer`) so the fallback 404 also produces an event, and `into_make_service_with_connect_info::<SocketAddr>()` so the middleware knows the socket IP.
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();
}`Config::from_env(service)` reads the variables below. Before `Arc::new` you can adjust the fields `api_key`, `api_url`, `service`, `env`, `skip_paths` (exact match; default `/health` and `/healthz`), `trust_trail_header` and `http` (the `reqwest::Client`, with a 5 s timeout).
| Variable | Required | Description |
|---|---|---|
| IMTBL_API_KEY | Yes | ImmutableLog API key, with the `events:write` scope |
| IMTBL_URL | No | API base URL (default `https://api.immutablelog.com`) |
| IMTBL_SERVICE_NAME | No | Service name (`meta.service`); default: the `from_env` argument |
| IMTBL_ENV | No | Environment (`meta.environment` and `meta.env`); default `production` |
Without `IMTBL_API_KEY`, the middleware logs a warning when building the `Config` and sends nothing.
Never hardcode IMTBL_API_KEY. Use an environment variable or a secrets manager.
How it works
before next.run
Copies method, path, MatchedPath, User-Agent, client_ip and, if enabled, the trail header
next.run(req).await
Runs the chain; the status comes out on the Response
tokio::spawn
Event sent in a separate task: the response does not wait
Idempotency-Key
A new UUID v4 per event, equal to meta.request_id. The incoming X-Request-Id is not used, because it comes from the caller and two different events with the same value would be discarded as a duplicate
body
The middleware never reads the request body: no content, no hash
Custom event and trail
In Axum the handler no longer has access to the request once it consumes it, so the `EventName` and `Trail` markers go in the response extensions. The middleware reads these markers after `next.run`.
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 })),
)
}Errors: Axum turns the error into a response before the middleware sees it, so `error_type` and `error_message` only appear if your error type's `IntoResponse` attaches an `ErrorInfo` (`ErrorInfo::from_error`). A 5xx response without `ErrorInfo` produces an event with `type: error`, but without `error_*`.
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
}
}Auto default: http.METHOD.path.
Immutable trail (immutable_trail)
A trail groups related events into a single auditable timeline and goes in `meta.immutable_trail`. Attach `Trail(...)` to a handler's response. The value goes through `sanitize_trail` before sending.
async fn run_flow(/* ... */) -> Response {
let mut res = Json(json!({ "status": "ok" })).into_response();
res.extensions_mut().insert(Trail("flow-123".into()));
res
}The trail cannot be empty, exceed 256 characters, or contain `:`, and violations return `400 invalid_immutable_trail`. That is why `sanitize_trail` replaces `:` with `-`, truncates at 256 and omits the key if it ends up empty.
The `X-Imtbl-Trail` header is optional and off by default. It is only read with `cfg.trust_trail_header = true` and only when the handler did not set a `Trail`. The header comes from whoever calls the service, so any caller could hang events on another caller's trail within the same tenant. Turn it on only when the service receives calls exclusively from your own internal services.
Response and status codes
The ingestion API is asynchronous. Success returns 202 (new) or 200 (idempotent duplicate). The middleware does not wait for this response (a rejection only produces a `tracing::warn!`), so these codes matter mostly if you send events manually.
| Status | Meaning |
|---|---|
| 202 | Event accepted and queued (new) |
| 200 | Idempotency-Key already exists (duplicate: true) |
| 400 | Missing/empty Idempotency-Key or invalid_immutable_trail |
| 403 | Inactive/expired subscription, scope or retention |
| 413 | payload_too_large (server limit: 16KB) |
| 429 | monthly_limit_exceeded, do not retry |
| 503 | mempool_full, transient, retryable |
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 meta | What it does in the SIEM |
|---|---|
event_name | The 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_ip | Becomes 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_trail | Becomes imtbl.immutable_trail, which groups related events for investigation (e.g. one order, one user). |
type | Event 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_message | Sent 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_id | Metadata: 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.ipwith 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.
client_ipX-Forwarded-For (1º hop)X-Real-IPconnection IPProvenance 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.
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
{
"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 integration behavior. For questions or advanced integrations, contact the support team.
