Rails Integration
Integrate ImmutableLog into any Rails application with a Rack middleware (Rails 7.1 or newer; tested on 7.1 and 8.1). The event is built still on the request thread and sent in a separate `Thread`: the response does not wait for ImmutableLog, and a send failure only produces a `warn` in `Rails.logger`. No controller needs to change.
Middleware code
There is no gem: copy the `immutable_log_middleware.rb` file from GitHub to `lib/immutable_log_middleware.rb`. It only uses the Ruby standard library (`net/http`, `json`, `ipaddr`, `securerandom`), Ruby 3.0+. An unhandled exception in the controller also produces an event, with status 500 and `error_*`.
# frozen_string_literal: true
# ImmutableLog Rack middleware for Rails (7.1+; works on 6.x/7.0 with the concrete path as
# http_route). Copy this file to lib/immutable_log_middleware.rb and register it in
# config/application.rb (see the README). Uses only the Ruby standard library.
require "ipaddr"
require "json"
require "logger"
require "net/http"
require "securerandom"
require "time"
require "uri"
class ImmutableLogMiddleware
DEFAULT_API_URL = "https://api.immutablelog.com"
MAX_ERROR_MESSAGE = 500
MAX_PATH = 2048
MAX_USER_AGENT = 512
MAX_TRAIL = 256
RETRYABLE = [408, 429, 500, 502, 503, 504].freeze
# Keys a controller sets in request.env to customise the event.
EVENT_NAME_KEY = "imtbl.event_name"
TRAIL_KEY = "imtbl.trail"
def initialize(app,
api_key: ENV["IMTBL_API_KEY"],
api_url: ENV["IMTBL_URL"],
service: ENV["IMTBL_SERVICE_NAME"],
env: ENV["IMTBL_ENV"],
skip_paths: %w[/health /healthz /up],
trust_trail_header: false,
timeout: 5,
logger: nil)
@app = app
@api_key = api_key.to_s
@endpoint = URI.join(blank?(api_url) ? DEFAULT_API_URL : api_url.to_s.chomp("/") + "/", "v1/events")
@service = blank?(service) ? "rails-service" : service.to_s
@env_name = blank?(env) ? "production" : env.to_s
@skip_paths = skip_paths.to_a.map(&:to_s).freeze
# X-Imtbl-Trail is controlled by whoever calls the service: off unless you opt in.
@trust_trail_header = trust_trail_header
@timeout = timeout
@logger = logger
log_warn("IMTBL_API_KEY is empty: no event will be sent") if @api_key.empty?
end
def call(env)
method = env["REQUEST_METHOD"].to_s
path = env["PATH_INFO"].to_s
# Preflight and skipped paths never generate an event.
return @app.call(env) if @api_key.empty? || method == "OPTIONS" || @skip_paths.include?(path)
facts = {
started: Process.clock_gettime(Process::CLOCK_MONOTONIC),
method: method.dup,
path: path[0, MAX_PATH],
user_agent: env["HTTP_USER_AGENT"].to_s[0, MAX_USER_AGENT],
client_ip: self.class.client_ip(env["HTTP_X_FORWARDED_FOR"], env["HTTP_X_REAL_IP"], env["REMOTE_ADDR"]),
header_trail: @trust_trail_header ? env["HTTP_X_IMTBL_TRAIL"]&.dup : nil,
}
begin
status, headers, body = @app.call(env)
rescue Exception => e # rubocop:disable Lint/RescueException -- re-raised right below
# The exception has not become a response yet: Rails' ShowExceptions answers it (500
# for most errors) after this middleware.
dispatch(facts, 500, env, e)
raise
end
dispatch(facts, status.to_i, env, nil)
[status, headers, body]
end
# client_ip for the SIEM: first entry of X-Forwarded-For, then X-Real-IP, then REMOTE_ADDR.
# Only a bare IP is returned (no port): the SIEM drops "ip:port" silently. The headers are
# read directly, without ActionDispatch::RemoteIp; see "Proxy e X-Forwarded-For" in the README.
def self.client_ip(xff, real_ip, remote_addr)
bare_ip(xff.to_s.split(",").first) || bare_ip(real_ip) || bare_ip(remote_addr)
end
# "203.0.113.7", "203.0.113.7:4711", "[2001:db8::1]:8080", "2001:db8::1" -> bare IP.
def self.bare_ip(raw)
s = raw.to_s.strip
return nil if s.empty? || s.include?("/") # IPAddr would accept a CIDR range
host =
if s.start_with?("[") then s[1...(s.index("]") || 1)].to_s
elsif s.count(":") == 1 then s.split(":").first.to_s
else s
end
ip = IPAddr.new(host)
(ip.ipv4_mapped? ? ip.native : ip).to_s # "::ffff:10.0.0.1" -> "10.0.0.1"
rescue IPAddr::Error, ArgumentError
nil
end
# The core rejects a trail that is empty, longer than 256 chars or contains ':'.
def self.sanitize_trail(value)
return nil if value.nil?
s = value.to_s.strip.tr(":", "-")[0, MAX_TRAIL]
s.empty? ? nil : s
end
private
# Reads what the app left in env (route, custom name, trail) here, on the request thread,
# and hands the background thread only plain strings, never env (copy, then spawn).
def dispatch(facts, status, env, exception)
event = build_event(facts, status, env, exception)
Thread.new { post(event) }
rescue StandardError => e
log_warn("failed to build event: #{e.message}")
end
def build_event(facts, status, env, exception)
kind = status >= 400 ? "error" : status >= 300 ? "info" : status >= 200 ? "success" : "info"
request_id = SecureRandom.uuid
latency_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - facts[:started]) * 1000).round
path = facts[:path]
event_name = (env[EVENT_NAME_KEY] || "http.#{facts[:method]}.#{path}").to_s
trail = self.class.sanitize_trail(env[TRAIL_KEY] || facts[:header_trail])
error_type = exception&.class&.name
error_message = exception&.message.to_s[0, MAX_ERROR_MESSAGE]
payload = {
"id" => SecureRandom.uuid,
"kind" => kind,
"message" => "#{facts[:method]} #{path} -> #{status}",
"timestamp" => Time.now.utc.iso8601,
"context" => { "ip" => facts[:client_ip] || "unknown", "user_agent" => facts[:user_agent] },
"request" => { "request_id" => request_id, "method" => facts[:method], "path" => path },
"metrics" => { "latency_ms" => latency_ms, "status_code" => status },
"severity" => kind == "error" ? "high" : "low",
}
if kind == "error"
payload["error"] = { "status_code" => status, "retryable" => RETRYABLE.include?(status) }
if error_type
payload["error"]["exception"] = error_type
payload["error"]["exception_message"] = error_message
end
end
# meta is a string -> string map in the core: every value goes through to_s
# (http_status is "200", never 200).
meta = {
"type" => kind,
"event_type" => kind,
"event_name" => event_name,
"service" => @service,
"request_id" => request_id,
# "env" is the legacy key; "environment" is the canonical one (CONTRACT.md §4.1).
"env" => @env_name,
"environment" => @env_name,
"http_method" => facts[:method],
"http_status" => status.to_s,
"http_route" => route_template(env) || path,
"log_level" => log_level(kind),
}
meta["client_ip"] = facts[:client_ip] if facts[:client_ip]
if error_type
meta["error_type"] = error_type
meta["error_message"] = error_message unless error_message.empty?
end
meta["immutable_trail"] = trail if trail
{ request_id: request_id, body: JSON.generate("payload" => JSON.generate(payload), "meta" => meta) }
end
# Route template from the Rails router (7.1+): "/users/:id(.:format)" -> "/users/:id".
# Rails 7.1/7.2 write it to env["action_dispatch.route_uri_pattern"]; Rails 8.1 only keeps the
# route object in env["action_dispatch.route"] and computes the pattern on demand in
# Request#route_uri_pattern, so the public method is asked first; the env key is the fallback.
# Missing on a 404 and on Rails < 7.1: the caller falls back to the concrete path.
def route_template(env)
pattern = nil
if defined?(ActionDispatch::Request) && ActionDispatch::Request.method_defined?(:route_uri_pattern)
pattern = ActionDispatch::Request.new(env).route_uri_pattern
end
pattern = env["action_dispatch.route_uri_pattern"] if blank?(pattern)
return nil if blank?(pattern)
pattern.to_s.sub(/\(\.:format\)\z/, "")
end
def post(event)
http = Net::HTTP.new(@endpoint.host, @endpoint.port)
http.use_ssl = @endpoint.scheme == "https"
http.open_timeout = [@timeout, 1].min
http.read_timeout = @timeout
http.write_timeout = @timeout
req = Net::HTTP::Post.new(@endpoint)
req["Content-Type"] = "application/json"
req["Authorization"] = "Bearer #{@api_key}"
req["Idempotency-Key"] = event[:request_id]
req.body = event[:body]
res = http.request(req)
log_warn("event rejected: HTTP #{res.code}") unless res.is_a?(Net::HTTPSuccess)
rescue StandardError => e
log_warn("failed to send event: #{e.class}: #{e.message}")
end
def log_level(kind)
{ "error" => "error", "warning" => "warn", "debug" => "debug" }.fetch(kind, "info")
end
def log_warn(msg)
logger = @logger || (defined?(Rails) && Rails.respond_to?(:logger) && Rails.logger) || (@fallback_logger ||= Logger.new($stderr))
logger.warn("[ImmutableLog] #{msg}")
end
def blank?(v)
v.nil? || v.to_s.strip.empty?
end
endMiddleware registration
Add the middleware to the Rack stack in `config/application.rb`. `config.middleware.use` puts the middleware at the end of the stack, right before the routes and after `ActionDispatch::ShowExceptions`: that is what makes the controller exception pass through it before it becomes the error page. Check with `bin/rails middleware`. Arguments (all optional): `api_key:`, `api_url:`, `service:`, `env:`, `skip_paths:` (exact match; default `/health`, `/healthz` and `/up`), `trust_trail_header:`, `timeout:` (seconds, default 5) and `logger:`.
# config/application.rb
require_relative "../lib/immutable_log_middleware"
module MyApp
class Application < Rails::Application
# ...
config.middleware.use ImmutableLogMiddleware,
service: "my-rails-api",
skip_paths: %w[/health /up /metrics]
end
end| 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 `rails-service` |
| IMTBL_ENV | No | Environment (`meta.environment` and `meta.env`); default `production` |
These are the defaults of the constructor arguments; whatever you pass to `config.middleware.use` wins over the variable. Without a key, the middleware logs a warning and sends nothing.
Never hardcode the key. Use an environment variable, `credentials.yml.enc` (`api_key: Rails.application.credentials.dig(:immutablelog, :api_key)`) or a secrets manager.
How it works
before @app.call
Copies method, path, User-Agent, client_ip and, if enabled, the trail header
@app.call(env)
Runs the routing and the controller; catches the exception and re-raises it (becomes a 500 event)
after
Reads status, route template (route_uri_pattern without the (.:format)) and env markers, and builds the event, still on the request thread
Thread.new
Sends in the background. The thread receives only strings, never the env
Idempotency-Key
A new UUID per event (SecureRandom.uuid), 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
Do not read the env inside the send Thread. The server reuses the env hash after the request ends, and what the thread reads later may belong to another request. That is why the middleware reads route, name and trail on the request thread and hands the Thread only strings.
Custom event and trail
In any controller, set `request.env["imtbl.event_name"]` and `request.env["imtbl.trail"]`. The middleware reads these values from `env` after the controller runs, when building the event.
class PaymentsController < ApplicationController
def create
request.env["imtbl.event_name"] = "payment.created"
request.env["imtbl.trail"] = "order-7782"
render json: { ok: true }, status: :created
end
endAuto default: http.METHOD.path.
Immutable trail (immutable_trail)
A trail groups related events into a single auditable timeline and goes in `meta.immutable_trail`. Set `request.env["imtbl.trail"]` in a controller. The value goes through `sanitize_trail` before sending.
def run
request.env["imtbl.trail"] = "flow-#{params[:id]}"
# ... business logic ...
render json: { status: "ok" }
endThe 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 `trust_trail_header: true`, and only when the controller did not set the 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). Sending runs in a `Thread` and a rejection only produces a `warn` in the log, 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.
require "ipaddr"
def bare_ip(value)
v = value.to_s.strip
if v.start_with?("[")
close = v.index("]")
return nil unless close
rest = v[(close + 1)..]
return nil unless rest.empty? || rest.match?(/\A:\d+\z/)
v = v[1...close]
elsif v.count(":") == 1
v = v.split(":", 2).first.to_s # 1.2.3.4:5678 -> 1.2.3.4
end
return nil if v.empty? || v.include?("%") || v.include?("/") # zona IPv6 e CIDR nao sao IP puro
IPAddr.new(v) # levanta IPAddr::Error se nao for IP (nao consulta DNS)
v
rescue IPAddr::Error
nil
end
# Candidatos na ordem: 1o item do X-Forwarded-For, X-Real-IP, IP de conexao.
def client_ip(request)
xff = request.get_header("HTTP_X_FORWARDED_FOR").to_s
ip = bare_ip(xff.split(",").first) unless xff.empty?
ip ||= bare_ip(request.get_header("HTTP_X_REAL_IP"))
ip || bare_ip(request.get_header("REMOTE_ADDR"))
end
meta = { event_name: "user.login" }
ip = client_ip(request)
meta[:client_ip] = ip if ip # sem IP valido, omita a chave (nunca "unknown")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.
