Pular para o conteúdo principal
ImmutableLog logo
← Voltar
LaravelPHP

Integração com Laravel

Integre o ImmutableLog em qualquer aplicação Laravel com um middleware global terminável. O `handle()` só marca o início; o evento é montado e enviado no `terminate()`, que o Laravel chama depois de entregar a resposta ao cliente. Uma falha de envio só gera um `Log::warning`. Leia a seção sobre PHP-FPM antes de usar em produção.

Instalação

Não há pacote Composer: você copia o arquivo `ImmutableLogMiddleware.php` do GitHub para `app/Http/Middleware/ImmutableLogMiddleware.php`. Ele usa só `ext-curl` e `ext-json` (presentes nas imagens oficiais do PHP) e o próprio Laravel (10 ou mais novo; testado no 13). PHP 8.1+. O arquivo declara `namespace App\Http\Middleware;`.

bash
app/Http/Middleware/ImmutableLogMiddleware.php   # conteúdo do ImmutableLogMiddleware.php

Código do middleware

Este é o arquivo inteiro. O `handle()` só marca o início da requisição (exceto `OPTIONS` e os `skip_paths`); o `terminate()` monta o evento e o envia depois da resposta. Exceção não tratada também gera evento, com status 500 e `error_*`.

php
<?php

// ImmutableLog middleware for Laravel (10, 11, 12).
//
// Copy this file to app/Http/Middleware/ImmutableLogMiddleware.php and register it as a
// global middleware (see the README). Uses only ext-curl and ext-json; no Composer package.

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

class ImmutableLogMiddleware
{
    private const DEFAULT_API_URL = 'https://api.immutablelog.com';
    private const DEFAULT_SKIP_PATHS = ['/health', '/healthz', '/up'];
    private const TIMEOUT_SECONDS = 5;
    private const MAX_ERROR_MESSAGE = 500;
    private const MAX_PATH = 2048;
    private const MAX_USER_AGENT = 512;
    private const MAX_TRAIL = 256;

    public function handle(Request $request, Closure $next): Response
    {
        if (! $this->skip($request)) {
            $request->attributes->set('imtbl.started_at', microtime(true));
        }

        return $next($request);
    }

    /**
     * Runs after the response was sent to the client (under PHP-FPM, after
     * fastcgi_finish_request()), so the POST to ImmutableLog never delays it.
     */
    public function terminate(Request $request, Response $response): void
    {
        if (! $request->attributes->has('imtbl.started_at')) {
            return; // skipped (OPTIONS, health) or the request never reached handle()
        }

        try {
            $apiKey = (string) $this->setting('key', 'IMTBL_API_KEY', '');
            if ($apiKey === '') {
                return;
            }
            $event = $this->buildEvent($request, $response);
            $this->send(
                rtrim((string) $this->setting('url', 'IMTBL_URL', self::DEFAULT_API_URL), '/').'/v1/events',
                $apiKey,
                $event['request_id'],
                $event['body']
            );
        } catch (\Throwable $e) {
            Log::warning('[ImmutableLog] failed to send event: '.$e->getMessage());
        }
    }

    private function skip(Request $request): bool
    {
        if ($request->isMethod('OPTIONS')) {
            return true;
        }
        $skip = config('services.immutablelog.skip_paths', self::DEFAULT_SKIP_PATHS);

        return in_array('/'.ltrim($request->path(), '/'), (array) $skip, true);
    }

    /** config('services.immutablelog.<key>') first (works with config:cache), then the env var. */
    private function setting(string $key, string $envName, string $default): string
    {
        $value = config("services.immutablelog.$key");
        if ($value === null || $value === '') {
            $value = env($envName);
        }

        return ($value === null || $value === '') ? $default : (string) $value;
    }

    /** @return array{request_id: string, body: string} */
    private function buildEvent(Request $request, Response $response): array
    {
        $status = $response->getStatusCode();
        $kind = $status >= 400 ? 'error' : ($status >= 300 ? 'info' : ($status >= 200 ? 'success' : 'info'));
        $method = $request->getMethod();
        $path = mb_substr('/'.ltrim($request->path(), '/'), 0, self::MAX_PATH);
        $requestId = (string) Str::uuid();
        $latencyMs = (int) round((microtime(true) - (float) $request->attributes->get('imtbl.started_at')) * 1000);
        $clientIp = self::clientIp(
            $request->headers->get('X-Forwarded-For'),
            $request->headers->get('X-Real-IP'),
            $request->server('REMOTE_ADDR')
        );
        $service = $this->setting('service', 'IMTBL_SERVICE_NAME', 'laravel-service');
        $env = $this->setting('env', 'IMTBL_ENV', 'production');

        // Route template: "users/{id}" from the matched route; null on a 404.
        $route = $request->route();
        $httpRoute = ($route !== null && method_exists($route, 'uri')) ? '/'.ltrim($route->uri(), '/') : $path;

        $eventName = $request->attributes->get('imtbl.event_name') ?: "http.$method.$path";
        $trailSource = $request->attributes->get('imtbl.trail');
        if ($trailSource === null && config('services.immutablelog.trust_trail_header', false)) {
            $trailSource = $request->headers->get('X-Imtbl-Trail');
        }
        $trail = self::sanitizeTrail($trailSource);

        // Laravel attaches the exception to the response it renders for it.
        $exception = property_exists($response, 'exception') ? $response->exception : null;
        $errorType = $exception instanceof \Throwable ? get_class($exception) : null;
        $errorMessage = $exception instanceof \Throwable ? $exception->getMessage() : null;

        $payload = [
            'id' => (string) Str::uuid(),
            'kind' => $kind,
            'message' => "$method $path -> $status",
            'timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
            'context' => [
                'ip' => $clientIp ?? 'unknown',
                'user_agent' => mb_substr((string) $request->userAgent(), 0, self::MAX_USER_AGENT),
            ],
            'request' => ['request_id' => $requestId, 'method' => $method, 'path' => $path],
            'metrics' => ['latency_ms' => $latencyMs, 'status_code' => $status],
            'severity' => $kind === 'error' ? 'high' : 'low',
        ];
        if ($kind === 'error') {
            $payload['error'] = [
                'status_code' => $status,
                'retryable' => in_array($status, [408, 429, 500, 502, 503, 504], true),
            ];
            if ($errorType !== null) {
                $payload['error']['exception'] = $errorType;
                $payload['error']['exception_message'] = mb_substr((string) $errorMessage, 0, self::MAX_ERROR_MESSAGE);
            }
        }

        // meta is a string -> string map in the core: every value is cast with (string).
        // http_status goes as "200", never as the integer 200.
        $meta = [
            'type' => $kind,
            'event_type' => $kind,
            'event_name' => (string) $eventName,
            'service' => (string) $service,
            'request_id' => $requestId,
            // "env" is the legacy key; "environment" is the canonical one (CONTRACT.md §4.1).
            'env' => (string) $env,
            'environment' => (string) $env,
            'http_method' => $method,
            'http_status' => (string) $status,
            'http_route' => (string) $httpRoute,
            'log_level' => self::logLevel($kind),
        ];
        if ($clientIp !== null) {
            $meta['client_ip'] = $clientIp;
        }
        if ($errorType !== null) {
            $meta['error_type'] = $errorType;
            if ((string) $errorMessage !== '') {
                $meta['error_message'] = mb_substr((string) $errorMessage, 0, self::MAX_ERROR_MESSAGE);
            }
        }
        if ($trail !== null) {
            $meta['immutable_trail'] = $trail;
        }

        $flags = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR;
        $body = json_encode(['payload' => json_encode($payload, $flags), 'meta' => $meta], $flags);

        return ['request_id' => $requestId, 'body' => $body];
    }

    private function send(string $url, string $apiKey, string $idempotencyKey, string $body): void
    {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $body,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer '.$apiKey,
                'Idempotency-Key: '.$idempotencyKey,
            ],
            CURLOPT_RETURNTRANSFER => true,
            // The send runs in terminate(), after the client got the response, but it still holds
            // the PHP-FPM worker until it finishes: keep the timeout short.
            CURLOPT_CONNECTTIMEOUT_MS => 1000,
            CURLOPT_TIMEOUT_MS => (int) ((float) config('services.immutablelog.timeout', self::TIMEOUT_SECONDS) * 1000),
        ]);
        $result = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        if ($result === false) {
            Log::warning('[ImmutableLog] failed to send event: '.curl_error($ch));
        } elseif ($status >= 400) {
            Log::warning("[ImmutableLog] event rejected: HTTP $status");
        }
        curl_close($ch);
    }

    /**
     * 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 TrustProxies; see "Proxy e X-Forwarded-For" in the README.
     */
    public static function clientIp(?string $xff, ?string $realIp, ?string $remoteAddr): ?string
    {
        $first = $xff !== null ? explode(',', $xff)[0] : null;

        return self::bareIp($first) ?? self::bareIp($realIp) ?? self::bareIp($remoteAddr);
    }

    /** "203.0.113.7", "203.0.113.7:4711", "[2001:db8::1]:8080", "2001:db8::1" -> bare IP. */
    private static function bareIp(?string $raw): ?string
    {
        $s = trim((string) $raw);
        if ($s === '') {
            return null;
        }
        if ($s[0] === '[') {
            $end = strpos($s, ']');
            $s = $end === false ? '' : substr($s, 1, $end - 1);
        } elseif (substr_count($s, ':') === 1) {
            $s = explode(':', $s)[0];
        }
        if (filter_var($s, FILTER_VALIDATE_IP) === false) {
            return null;
        }
        // "::ffff:10.0.0.1" -> "10.0.0.1"
        if (stripos($s, '::ffff:') === 0 && filter_var(substr($s, 7), FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
            return substr($s, 7);
        }

        return $s;
    }

    /** The core rejects a trail that is empty, longer than 256 chars or contains ':'. */
    private static function sanitizeTrail(mixed $value): ?string
    {
        if (! is_scalar($value)) {
            return null;
        }
        $s = mb_substr(str_replace(':', '-', trim((string) $value)), 0, self::MAX_TRAIL);

        return $s === '' ? null : $s;
    }

    private static function logLevel(string $kind): string
    {
        return match ($kind) {
            'error' => 'error',
            'warning' => 'warn',
            'debug' => 'debug',
            default => 'info',
        };
    }
}

Registro do middleware

No Laravel 11 ou mais novo, registre no `bootstrap/app.php`. No Laravel 10, adicione à propriedade `$middleware` do `app/Http/Kernel.php`. Precisa ser global: o `terminate()` só roda para middleware registrado no kernel.

php
<?php
// Laravel 11 ou mais novo: bootstrap/app.php
use App\Http\Middleware\ImmutableLogMiddleware;

return Application::configure(basePath: dirname(__DIR__))
    // ...
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->append(ImmutableLogMiddleware::class);   // global
    })
    ->create();

// Laravel 10: app/Http/Kernel.php
// protected $middleware = [
//     // ...
//     \App\Http\Middleware\ImmutableLogMiddleware::class,
// ];

O middleware lê primeiro `config('services.immutablelog.*')` e só depois `env()`. Use o `config/services.php`: com `php artisan config:cache` o `.env` não é mais carregado em tempo de execução, e só a config sobrevive.

php
// config/services.php
'immutablelog' => [
    'key'     => env('IMTBL_API_KEY'),
    'url'     => env('IMTBL_URL', 'https://api.immutablelog.com'),
    'service' => env('IMTBL_SERVICE_NAME', 'laravel-service'),
    'env'     => env('IMTBL_ENV', 'production'),
    'timeout' => 2,                       // segundos; ver a seção sobre PHP-FPM
    // 'skip_paths' => ['/health', '/up'],
    // 'trust_trail_header' => false,
],

# .env
IMTBL_API_KEY=iml_live_xxxxxxxxxxxxxxxx
IMTBL_SERVICE_NAME=meu-servico-laravel
IMTBL_ENV=production
VariávelObrigatóriaDescrição
IMTBL_API_KEYSimChave de API do ImmutableLog, com scope `events:write`
IMTBL_URLNãoURL base da API (padrão `https://api.immutablelog.com`)
IMTBL_SERVICE_NAMENãoNome do serviço (`meta.service`); padrão `laravel-service`
IMTBL_ENVNãoAmbiente (`meta.environment` e `meta.env`); padrão `production`

Sem chave, o middleware não envia nada. As chaves opcionais de `services.immutablelog` são `skip_paths` (comparação exata; padrão `/health`, `/healthz` e `/up`), `trust_trail_header` e `timeout` (segundos; padrão 5).

Nunca coloque a chave no código nem no repositório: mantenha o .env fora do git, ou use um secrets manager. O `php artisan serve` só repassa ao servidor embutido as variáveis do .env e uma lista fixa; uma IMTBL_API_KEY exportada só no shell não chega ao PHP. O PHP-FPM, por padrão (`clear_env = yes`), também descarta o ambiente do processo. Nos dois casos, use o .env ou o config/services.php.

Como funciona

handle()

Marca imtbl.started_at nos atributos da request (exceto OPTIONS e skip_paths)

next($request)

A aplicação processa e a resposta é enviada ao cliente

terminate()

Lê status, rota, exceção e marcadores; monta o evento; POST via cURL

Idempotency-Key

Um UUID novo por evento (Str::uuid()), 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

Envio, PHP-FPM e o tempo de resposta

PHP não tem thread em segundo plano: o POST roda no mesmo processo, no `terminate()`. O modo de servir a aplicação muda o efeito.

Como é servidaEfeito do envio
PHP-FPMO cliente recebe a resposta sem esperar o envio (o `fastcgi_finish_request()` roda antes). Mas o worker do FPM fica ocupado até o envio terminar, no máximo o timeout. Com o ImmutableLog lento, os workers ficam presos e as requisições seguintes esperam na fila do pool (o padrão são 5 workers).
php artisan serve / php -SNão há `fastcgi_finish_request()`: a conexão só fecha depois do envio. Com o ImmutableLog lento, cada resposta atrasa até o timeout (medido: 5 s com o core travado). Use só em desenvolvimento.

Mantenha o timeout baixo (`services.immutablelog.timeout`, em segundos; o padrão do arquivo é 5) e dimensione o pool do FPM. Para isolar de vez, mova o envio para uma fila (um job via `dispatch()`), o que não está neste arquivo. Com o ImmutableLog fora do ar (conexão recusada), não há efeito visível.

Evento e trilha customizados

Defina os atributos `imtbl.event_name` e `imtbl.trail` na request dentro de qualquer controller ou closure de rota. O `terminate()` lê esses valores ao montar o evento.

php
public function store(Request $request)
{
    $request->attributes->set('imtbl.event_name', 'payment.created');
    $request->attributes->set('imtbl.trail', 'order-7782');

    return response()->json(['ok' => true], 201);
}

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 o atributo `imtbl.trail` na request. O valor passa por `sanitizeTrail` antes do envio.

php
Route::post('/flows/{id}/run', function (Request $request, string $id) {
    $request->attributes->set('imtbl.trail', "flow-{$id}");
    // ... business logic ...
    return response()->json(['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 `'trust_trail_header' => true` em `config/services.php`, e só quando o controller 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 envio acontece em `terminate()` e uma recusa só gera um `Log::warning`, então esses códigos importam principalmente se você enviar eventos manualmente.

StatusSignificado
202Evento aceito e enfileirado (novo)
200Idempotency-Key já existente (duplicate: true)
400Idempotency-Key ausente/vazia ou invalid_immutable_trail
403Assinatura inativa/expirada, escopo ou retenção
413payload_too_large (limite do servidor: 16KB)
429monthly_limit_exceeded, não fazer retry
503mempool_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 metaO que faz no SIEM
event_nameO 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_ipVira 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_trailVira imtbl.immutable_trail, que agrupa eventos relacionados para investigação (ex.: um pedido, um usuário).
typeSeveridade 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_messageEnviados pelos middlewares, sempre como string (inclusive http_status, ex.: "200"). error_type e error_message só existem quando há erro.
service, env, request_idMetadados: 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.ip com 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.
Precedência de source.ip:client_ipX-Forwarded-For (1º hop)X-Real-IPIP de conexão

Proveniê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.

php
function bare_ip(?string $value): ?string {
    $v = trim((string) $value);
    if ($v === '') return null;
    if ($v[0] === '[') {
        $end = strpos($v, ']');
        if ($end === false) return null;
        $rest = substr($v, $end + 1);
        if ($rest !== '' && !preg_match('/^:\d+$/', $rest)) return null;
        $v = substr($v, 1, $end - 1);
    } elseif (substr_count($v, ':') === 1) {
        $v = explode(':', $v, 2)[0]; // 1.2.3.4:5678 -> 1.2.3.4
    }
    if (strpos($v, '%') !== false) return null; // zona IPv6 (fe80::1%eth0) nao e IP puro
    return filter_var($v, FILTER_VALIDATE_IP) !== false ? $v : null;
}

// Candidatos na ordem: 1o item do X-Forwarded-For, X-Real-IP, IP de conexao.
function client_ip(): ?string {
    $xff = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '';
    if ($xff !== '' && ($ip = bare_ip(explode(',', $xff)[0])) !== null) return $ip;
    if (($ip = bare_ip($_SERVER['HTTP_X_REAL_IP'] ?? null)) !== null) return $ip;
    return bare_ip($_SERVER['REMOTE_ADDR'] ?? null);
}

$meta = ['event_name' => 'user.login'];
$ip = client_ip();
if ($ip !== null) {
    $meta['client_ip'] = $ip; // sem IP valido, omita a chave (nunca "unknown")
}

Exemplo de payload

json
{
  "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.

Voltar para PHP