Skip to main content
ImmutableLog logo
Back
Minimal APIC#

Minimal API Integration

Minimal API uses the same HTTP pipeline as ASP.NET Core, so it reuses exactly the same `ImmutableLogMiddleware`. The difference is the functional registration in `Program.cs` and how you set the event and trail per endpoint via `HttpContext.Items`.

Reuse the middleware

The middleware code is identical to the ASP.NET Core page — copy `ImmutableLogMiddleware.cs` from there. Here we only show the registration and usage in Minimal API endpoints.

Registration in Program.cs

Register the options, the `IHttpClientFactory`, and the middleware. Order matters: call `UseMiddleware` before mapping the endpoints.

csharp
// Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHttpClient("immutablelog", c => c.Timeout = TimeSpan.FromSeconds(5));
builder.Services.AddSingleton(new ImmutableLogOptions
{
    ApiKey = Environment.GetEnvironmentVariable("IMTBL_API_KEY") ?? "",
    Service = "my-minimal-api",
    Env = builder.Environment.EnvironmentName,
    SkipPaths = new() { "/health", "/metrics" },
});
builder.Services.AddSingleton<ImmutableLogMiddleware>();

var app = builder.Build();

// Registre antes de mapear os endpoints.
app.UseMiddleware<ImmutableLogMiddleware>();

app.MapGet("/health", () => Results.Ok(new { ok = true }));
app.MapGet("/users", () => Results.Ok(new[] { "alice", "bob" }));

app.Run();

Never hardcode the token. Load IMTBL_API_KEY from environment variables or user-secrets in development.

Event and trail per endpoint

Receive the `HttpContext` in the endpoint delegate and set `Items["imtbl.eventName"]` and `Items["imtbl.trail"]`. The middleware reads these values when emitting the event.

csharp
// Receba o HttpContext para definir evento/trilha por endpoint.
app.MapPost("/payments", (HttpContext ctx, PaymentDto dto) =>
{
    ctx.Items["imtbl.eventName"] = "payment.created";
    ctx.Items["imtbl.trail"] = "order-7782";

    // ... business logic ...
    return Results.Ok(new { ok = true, payment_id = "pay_123" });
});

// Trilha por fluxo de negócio:
app.MapPost("/flows/{id}/run", (HttpContext ctx, string id) =>
{
    ctx.Items["imtbl.trail"] = $"flow-{id}";
    return Results.Ok(new { status = "ok" });
});

Auto default: http.METHOD.path.

Immutable trail (immutable_trail)

A trail groups related events into a single auditable timeline. Set `ctx.Items["imtbl.trail"]` in the endpoint delegate, or propagate it across services with the `X-Imtbl-Trail` header. The value is normalized by the middleware before sending.

The trail cannot be empty, exceed 256 characters, or contain `:` — violations return `400 invalid_immutable_trail`. The middleware's `SanitizeTrail` fixes the value before sending.

Response and status codes

The ingestion API is asynchronous. Success returns 202 (new) or 200 (idempotent duplicate). Since the middleware is fire-and-forget, these codes matter mostly if you send events manually.

StatusMeaning
202Event accepted and queued (new)
200Idempotency-Key already exists — duplicate: true
400Missing/empty Idempotency-Key or invalid_immutable_trail
403Inactive/expired subscription, scope or retention
413payload_too_large (server limit: 16KB)
429monthly_limit_exceeded — do not retry
503mempool_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 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 loginauthentication).
client_ipBecomes source.ip with maximum precedence and provenance client_asserted. See the section below.
immutable_trailBecomes imtbl.immutable_trail — 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.)
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 — it does not drop the event.
  • 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 is spoofable by whoever controls that backend. However it is self-contained to 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

Take the first IP from X-Forwarded-For (closest to the user); as a fallback, use the connection IP.

csharp
static string? ClientIp(HttpContext ctx)
{
    var xff = ctx.Request.Headers["X-Forwarded-For"].ToString();
    if (!string.IsNullOrEmpty(xff))
        return xff.Split(',')[0].Trim(); // primeiro hop = IP do usuario
    return ctx.Connection.RemoteIpAddress?.ToString();
}

var meta = new Dictionary<string, string>
{
    ["event_name"] = "user.login",
    ["client_ip"] = ClientIp(ctx) ?? "",
};

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 integration behavior. For questions or advanced integrations, contact the support team.