Integração com ASP.NET Core
Integre o ImmutableLog em qualquer aplicação ASP.NET Core com um middleware `IMiddleware` que captura as requisições HTTP (exceto `OPTIONS` e os paths de `SkipPaths`). O mesmo arquivo serve MVC/controllers e Minimal API. O envio roda em `Task.Run`: a resposta não espera o ImmutableLog, e uma falha de envio só gera um `LogWarning`.
Código do middleware
Não há pacote NuGet: copie o arquivo `ImmutableLogMiddleware.cs` do GitHub para o seu projeto (ex.: `Infrastructure/ImmutableLogMiddleware.cs`). Ele usa só o shared framework do ASP.NET Core (.NET 6 ou mais novo, projeto `Microsoft.NET.Sdk.Web`). O arquivo declara `namespace ImmutableLog;`: importe com `using ImmutableLog;` ou troque o namespace pelo seu. Exceção não tratada também gera evento, com status 500 e `error_*`.
// ImmutableLog middleware for ASP.NET Core (.NET 6+): MVC/controllers and Minimal API.
//
// Copy this file into your project and register it:
// builder.Services.AddImmutableLog(o => o.Service = "my-api");
// app.UseImmutableLog();
// Only the ASP.NET Core shared framework is needed (no NuGet package).
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace ImmutableLog;
public sealed class ImmutableLogOptions
{
public string ApiKey { get; set; } = FromEnv("IMTBL_API_KEY") ?? "";
public string ApiUrl { get; set; } = FromEnv("IMTBL_URL") ?? "https://api.immutablelog.com";
public string Service { get; set; } = FromEnv("IMTBL_SERVICE_NAME") ?? "aspnet-service";
public string Env { get; set; } = FromEnv("IMTBL_ENV") ?? "production";
/// <summary>Exact paths that never generate an event.</summary>
public HashSet<string> SkipPaths { get; set; } = new(StringComparer.Ordinal) { "/health", "/healthz" };
/// <summary>
/// Read <c>X-Imtbl-Trail</c> from the incoming request when the endpoint sets no trail.
/// Off by default: the header is controlled by whoever calls the service.
/// </summary>
public bool TrustTrailHeader { get; set; }
public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(5);
private static string? FromEnv(string name)
{
var v = Environment.GetEnvironmentVariable(name);
return string.IsNullOrWhiteSpace(v) ? null : v;
}
}
/// <summary>Keys an endpoint sets in <c>HttpContext.Items</c> to customise the event.</summary>
public static class ImmutableLogItems
{
public const string EventName = "imtbl.eventName";
public const string Trail = "imtbl.trail";
}
public sealed class ImmutableLogMiddleware : IMiddleware
{
internal const string HttpClientName = "immutablelog";
private const int MaxErrorMessage = 500;
private const int MaxPath = 2048;
private const int MaxUserAgent = 512;
private const int MaxTrail = 256;
private readonly IHttpClientFactory _httpFactory;
private readonly ImmutableLogOptions _opts;
private readonly ILogger<ImmutableLogMiddleware> _log;
public ImmutableLogMiddleware(IHttpClientFactory httpFactory, ImmutableLogOptions opts, ILogger<ImmutableLogMiddleware> log)
{
_httpFactory = httpFactory;
_opts = opts;
_log = log;
if (string.IsNullOrEmpty(opts.ApiKey))
log.LogWarning("[ImmutableLog] IMTBL_API_KEY is empty: no event will be sent");
}
public async Task InvokeAsync(HttpContext ctx, RequestDelegate next)
{
var req = ctx.Request;
// Preflight and skipped paths never generate an event.
if (HttpMethods.IsOptions(req.Method) || _opts.SkipPaths.Contains(req.Path.Value ?? ""))
{
await next(ctx);
return;
}
var started = Stopwatch.GetTimestamp();
var method = req.Method;
var path = req.Path.Value ?? "/";
var userAgent = req.Headers.UserAgent.ToString();
var clientIp = ClientIp(req.Headers["X-Forwarded-For"].ToString(), req.Headers["X-Real-IP"].ToString(),
ctx.Connection.RemoteIpAddress);
var headerTrail = _opts.TrustTrailHeader ? req.Headers["X-Imtbl-Trail"].ToString() : null;
Exception? caught = null;
try
{
await next(ctx);
}
catch (Exception ex)
{
caught = ex;
throw;
}
finally
{
// Everything is copied out of the HttpContext HERE, on the request thread: the
// context is pooled and recycled once the request ends, so the background send
// below never touches it.
try
{
// An exception that escapes the pipeline has not become a response yet: the
// server answers it with 500. If the response already started, its status stands.
var status = caught != null && !ctx.Response.HasStarted ? 500 : ctx.Response.StatusCode;
// UseExceptionHandler registered after this middleware swallows the exception and
// leaves it in IExceptionHandlerFeature.
var error = caught ?? ctx.Features.Get<IExceptionHandlerFeature>()?.Error;
var evt = new EventFacts(
Method: method,
Path: path,
// Route template: "/users/{id}" (Minimal API) or "users/{id}" (attribute routing,
// normalised to a leading "/"). No RouteEndpoint on a 404: falls back to the path.
Route: RouteTemplate(ctx.GetEndpoint()),
Status: status,
LatencyMs: (long)Stopwatch.GetElapsedTime(started).TotalMilliseconds,
UserAgent: userAgent,
ClientIp: clientIp,
EventName: ctx.Items[ImmutableLogItems.EventName] as string,
Trail: ctx.Items[ImmutableLogItems.Trail] as string ?? headerTrail,
ErrorType: error?.GetType().FullName,
ErrorMessage: error?.Message);
if (!string.IsNullOrEmpty(_opts.ApiKey))
_ = Task.Run(() => SendAsync(evt)); // fire and forget: never delays the response
}
catch (Exception ex)
{
_log.LogWarning(ex, "[ImmutableLog] failed to build event");
}
}
}
private sealed record EventFacts(
string Method, string Path, string? Route, int Status, long LatencyMs, string UserAgent,
string? ClientIp, string? EventName, string? Trail, string? ErrorType, string? ErrorMessage);
private async Task SendAsync(EventFacts e)
{
try
{
var kind = e.Status >= 400 ? "error" : e.Status >= 300 ? "info" : e.Status >= 200 ? "success" : "info";
var requestId = Guid.NewGuid().ToString();
var path = Truncate(e.Path, MaxPath);
var eventName = string.IsNullOrEmpty(e.EventName) ? $"http.{e.Method}.{path}" : e.EventName;
var trail = SanitizeTrail(e.Trail);
var payload = new Dictionary<string, object?>
{
["id"] = Guid.NewGuid().ToString(),
["kind"] = kind,
["message"] = $"{e.Method} {path} -> {e.Status}",
["timestamp"] = DateTimeOffset.UtcNow.ToString("o"),
["context"] = new Dictionary<string, object?>
{
["ip"] = e.ClientIp ?? "unknown",
["user_agent"] = Truncate(e.UserAgent, MaxUserAgent),
},
["request"] = new Dictionary<string, object?>
{
["request_id"] = requestId, ["method"] = e.Method, ["path"] = path,
},
["metrics"] = new Dictionary<string, object?>
{
["latency_ms"] = e.LatencyMs, ["status_code"] = e.Status,
},
["severity"] = kind == "error" ? "high" : "low",
};
if (kind == "error")
{
var err = new Dictionary<string, object?>
{
["status_code"] = e.Status,
["retryable"] = e.Status is 408 or 429 or 500 or 502 or 503 or 504,
};
if (e.ErrorType != null)
{
err["exception"] = e.ErrorType;
err["exception_message"] = Truncate(e.ErrorMessage ?? "", MaxErrorMessage);
}
payload["error"] = err;
}
// meta is a string -> string map in the core: Dictionary<string, string>, never object.
var meta = new Dictionary<string, string>
{
["type"] = kind,
["event_type"] = kind,
["event_name"] = eventName,
["service"] = _opts.Service,
["request_id"] = requestId,
// "env" is the legacy key; "environment" is the canonical one (CONTRACT.md §4.1).
["env"] = _opts.Env,
["environment"] = _opts.Env,
["http_method"] = e.Method,
["http_status"] = e.Status.ToString(System.Globalization.CultureInfo.InvariantCulture),
["http_route"] = string.IsNullOrEmpty(e.Route) ? path : e.Route,
["log_level"] = kind == "error" ? "error" : kind == "warning" ? "warn" : kind == "debug" ? "debug" : "info",
};
if (e.ClientIp != null) meta["client_ip"] = e.ClientIp;
if (e.ErrorType != null)
{
meta["error_type"] = e.ErrorType;
if (!string.IsNullOrEmpty(e.ErrorMessage)) meta["error_message"] = Truncate(e.ErrorMessage, MaxErrorMessage);
}
if (trail != null) meta["immutable_trail"] = trail;
var body = JsonSerializer.Serialize(new Dictionary<string, object>
{
["payload"] = JsonSerializer.Serialize(payload),
["meta"] = meta,
});
using var msg = new HttpRequestMessage(HttpMethod.Post, _opts.ApiUrl.TrimEnd('/') + "/v1/events")
{
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
msg.Headers.TryAddWithoutValidation("Authorization", "Bearer " + _opts.ApiKey);
msg.Headers.TryAddWithoutValidation("Idempotency-Key", requestId);
var http = _httpFactory.CreateClient(HttpClientName);
using var res = await http.SendAsync(msg);
if (!res.IsSuccessStatusCode)
_log.LogWarning("[ImmutableLog] event rejected: HTTP {Status}", (int)res.StatusCode);
}
catch (Exception ex)
{
_log.LogWarning("[ImmutableLog] failed to send event: {Message}", ex.Message);
}
}
private static string? RouteTemplate(Endpoint? endpoint)
{
var raw = (endpoint as RouteEndpoint)?.RoutePattern.RawText;
if (string.IsNullOrEmpty(raw)) return null;
return raw.StartsWith('/') ? raw : "/" + raw;
}
/// <summary>
/// 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.
/// </summary>
internal static string? ClientIp(string xff, string realIp, IPAddress? peer)
{
var first = xff.Split(',')[0];
return BareIp(first) ?? BareIp(realIp) ?? (peer != null ? Canonical(peer).ToString() : null);
}
/// <summary>"203.0.113.7", "203.0.113.7:4711", "[2001:db8::1]:8080", "2001:db8::1" -> bare IP.</summary>
private static string? BareIp(string? raw)
{
var s = (raw ?? "").Trim();
if (s.Length == 0) return null;
string host;
if (s.StartsWith('['))
{
var end = s.IndexOf(']');
host = end > 0 ? s.Substring(1, end - 1) : "";
}
else if (s.Count(c => c == ':') == 1) host = s[..s.IndexOf(':')];
else host = s;
// IPAddress.TryParse accepts legacy forms like "12345"; require a real IPv4/IPv6 shape.
if (!host.Contains('.') && !host.Contains(':')) return null;
return IPAddress.TryParse(host, out var ip) ? Canonical(ip).ToString() : null;
}
/// <summary>"::ffff:10.0.0.1" (Kestrel on a dual-stack socket) -> "10.0.0.1".</summary>
private static IPAddress Canonical(IPAddress ip) =>
ip.AddressFamily == AddressFamily.InterNetworkV6 && ip.IsIPv4MappedToIPv6 ? ip.MapToIPv4() : ip;
/// <summary>The core rejects a trail that is empty, longer than 256 chars or contains ':'.</summary>
private static string? SanitizeTrail(string? v)
{
if (v == null) return null;
var s = v.Trim().Replace(':', '-');
if (s.Length > MaxTrail) s = s[..MaxTrail];
return s.Length == 0 ? null : s;
}
private static string Truncate(string s, int max) => s.Length > max ? s[..max] : s;
}
public static class ImmutableLogExtensions
{
/// <summary>Registers the options, the named HttpClient and the middleware.</summary>
public static IServiceCollection AddImmutableLog(this IServiceCollection services, Action<ImmutableLogOptions>? configure = null)
{
var opts = new ImmutableLogOptions();
configure?.Invoke(opts);
services.AddSingleton(opts);
services.AddHttpClient(ImmutableLogMiddleware.HttpClientName, c => c.Timeout = opts.Timeout);
services.AddSingleton<ImmutableLogMiddleware>();
return services;
}
/// <summary>Adds the middleware to the pipeline. Register it early, before the endpoints.</summary>
public static IApplicationBuilder UseImmutableLog(this IApplicationBuilder app) =>
app.UseMiddleware<ImmutableLogMiddleware>();
}Registro e Configuração
`AddImmutableLog` registra o `ImmutableLogOptions` como singleton, um `HttpClient` nomeado `immutablelog` (timeout de `o.Timeout`) e o middleware. `UseImmutableLog` entra cedo no pipeline, antes dos endpoints. Se preferir registrar à mão: `services.AddSingleton(new ImmutableLogOptions { ... })`, `services.AddHttpClient("immutablelog")`, `services.AddSingleton<ImmutableLogMiddleware>()` e `app.UseMiddleware<ImmutableLogMiddleware>()`.
// Program.cs
using ImmutableLog;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddImmutableLog(o =>
{
o.Service = "my-aspnet-service";
o.Env = builder.Environment.EnvironmentName;
o.SkipPaths.Add("/metrics");
});
var app = builder.Build();
app.UseImmutableLog(); // cedo no pipeline, antes dos endpoints
app.MapControllers();
app.Run();Os valores padrão de `ImmutableLogOptions` vêm das variáveis abaixo. O que você atribuir em `AddImmutableLog(o => ...)` vale sobre a variável. Opções: `ApiKey`, `ApiUrl`, `Service`, `Env`, `SkipPaths` (comparação exata; padrão `/health` e `/healthz`), `TrustTrailHeader` e `Timeout` (padrão 5 s).
| Variável | Obrigatória | Descrição |
|---|---|---|
| IMTBL_API_KEY | Sim | Chave de API do ImmutableLog, com scope `events:write` |
| IMTBL_URL | Não | URL base da API (padrão `https://api.immutablelog.com`) |
| IMTBL_SERVICE_NAME | Não | Nome do serviço (`meta.service`); padrão `aspnet-service` |
| IMTBL_ENV | Não | Ambiente (`meta.environment` e `meta.env`); padrão `production` |
Sem chave, o middleware registra um aviso na criação e não envia nada.
Nunca coloque a chave no código. Use variável de ambiente, `dotnet user-secrets` em desenvolvimento, ou um secrets manager.
Como funciona
antes de next(ctx)
Copia método, path, User-Agent, client_ip e, se ligado, o header de trilha
await next(ctx)
Executa o resto do pipeline; captura a exceção e a relança
finally
Lê status, RouteEndpoint, Items e o erro, e monta o evento, tudo ainda na thread da requisição
Task.Run(SendAsync)
Envia em segundo plano. O HttpContext nunca é tocado depois da requisição
Idempotency-Key
Um GUID 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
Não leia o HttpContext dentro da Task de envio. O servidor recicla o contexto assim que a requisição termina, e o código lido depois pode devolver dados de outra requisição ou falhar. Por isso o middleware copia tudo no finally, antes de disparar o Task.Run.
Evento e trilha customizados
Defina `HttpContext.Items[ImmutableLogItems.EventName]` (literal `"imtbl.eventName"`) e `HttpContext.Items[ImmutableLogItems.Trail]` (literal `"imtbl.trail"`) em qualquer controller ou endpoint. O middleware lê esses valores no `finally`, quando monta o evento.
[ApiController]
public class PaymentsController : ControllerBase
{
[HttpPost("payments")]
public IActionResult Create()
{
HttpContext.Items[ImmutableLogItems.EventName] = "payment.created";
HttpContext.Items[ImmutableLogItems.Trail] = "order-7782";
return StatusCode(201, new { ok = true });
}
}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`. Defina `HttpContext.Items[ImmutableLogItems.Trail]` em um endpoint. O valor passa por `SanitizeTrail` antes do envio.
[HttpPost("flows/{id}/run")]
public IActionResult RunFlow(string id)
{
HttpContext.Items[ImmutableLogItems.Trail] = $"flow-{id}";
// ... business logic ...
return Ok(new { status = "ok" });
}A trilha não pode ser vazia, exceder 256 caracteres ou conter `:`, e violações retornam `400 invalid_immutable_trail`. Por isso o `SanitizeTrail` 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 `o.TrustTrailHeader = true` e só quando o endpoint não definiu a trilha. 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 `LogWarning`), então esses códigos importam principalmente se você enviar eventos manualmente.
| Status | Significado |
|---|---|
| 202 | Evento aceito e enfileirado (novo) |
| 200 | Idempotency-Key já existente (duplicate: true) |
| 400 | Idempotency-Key ausente/vazia ou invalid_immutable_trail |
| 403 | Assinatura inativa/expirada, escopo ou retenção |
| 413 | payload_too_large (limite do servidor: 16KB) |
| 429 | monthly_limit_exceeded, não fazer retry |
| 503 | mempool_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 meta | O que faz no SIEM |
|---|---|
event_name | O 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_ip | Vira 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_trail | Vira imtbl.immutable_trail, que agrupa eventos relacionados para investigação (ex.: um pedido, um usuário). |
type | Severidade 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_message | Enviados pelos middlewares, sempre como string (inclusive http_status, ex.: "200"). error_type e error_message só existem quando há erro. |
service, env, request_id | Metadados: 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.ipcom 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.
client_ipX-Forwarded-For (1º hop)X-Real-IPIP de conexãoProveniê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.
using System.Net;
static string? BareIp(string? value)
{
var v = (value ?? "").Trim();
if (v.StartsWith('['))
{
var end = v.IndexOf(']');
if (end < 0) return null;
var rest = v[(end + 1)..];
if (rest.Length > 0 && !(rest.Length > 1 && rest[0] == ':' && rest[1..].All(char.IsAsciiDigit))) return null;
v = v[1..end];
}
else if (v.Count(c => c == ':') == 1)
{
v = v[..v.IndexOf(':')]; // 1.2.3.4:5678 -> 1.2.3.4
}
// TryParse aceita formas curtas ("1" vira 0.0.0.1): exija 4 octetos ou um IPv6 (com ':').
if (v.Contains('%') || !IPAddress.TryParse(v, out var ip)) return null;
if (!v.Contains(':') && v.Count(c => c == '.') != 3) return null;
if (ip.IsIPv4MappedToIPv6) ip = ip.MapToIPv4(); // ::ffff:1.2.3.4 -> 1.2.3.4
return ip.ToString();
}
// Candidatos na ordem: 1o item do X-Forwarded-For, X-Real-IP, IP de conexao.
static string? ClientIp(HttpContext ctx)
{
var xff = ctx.Request.Headers["X-Forwarded-For"].ToString();
if (xff.Length > 0 && BareIp(xff.Split(',')[0]) is { } fromXff) return fromXff;
if (BareIp(ctx.Request.Headers["X-Real-IP"].ToString()) is { } fromXri) return fromXri;
return BareIp(ctx.Connection.RemoteIpAddress?.ToString());
}
var meta = new Dictionary<string, string> { ["event_name"] = "user.login" };
if (ClientIp(ctx) is { } ip)
meta["client_ip"] = ip; // sem IP valido, omita a chave (nunca "unknown")Exemplo de payload
{
"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.
