fix(http): restrict trusted proxy headers to Traefik and prefer X-Real-Ip

This commit is contained in:
Jérémy Munsch 2026-11-14 22:35:08 +01:00
parent 4771ef9a72
commit 3c34f4af28
No known key found for this signature in database
GPG key ID: 2AAECDA6B7330F91
3 changed files with 67 additions and 1 deletions

View file

@ -47,6 +47,12 @@ class AppServiceProvider extends ServiceProvider
);
$this->app->singleton('clientIp', function () {
$realIp = request()->header('X-Real-Ip');
if (\is_string($realIp) && \filter_var($realIp, \FILTER_VALIDATE_IP) !== false) {
return $realIp;
}
return request()->ip() ?? request()->getClientIp();
});

View file

@ -57,7 +57,10 @@ $redirectUsers = function (Request $request) {
};
return function (Middleware $middleware) use ($redirectGuests, $redirectUsers): void {
$middleware->trustProxies(at: '*');
$middleware->trustProxies(
at: '*',
headers: Request::HEADER_X_FORWARDED_TRAEFIK,
);
$middleware->redirectGuestsTo($redirectGuests);
$middleware->redirectUsersTo($redirectUsers);

View file

@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
use Illuminate\Http\Request;
describe('TrustProxies and clientIp resolution', function (): void {
it('resolves clientIp from valid X-Real-Ip header when present', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
$request = Request::create('/', 'GET', [], [], [], [
'HTTP_X_REAL_IP' => '203.0.113.42',
'HTTP_X_FORWARDED_FOR' => '198.51.100.10',
]);
$this->app->instance('request', $request);
$this->app->forgetInstance('clientIp');
// WHEN
$clientIp = $this->app->make('clientIp');
// THEN
expect($clientIp)->toBe('203.0.113.42');
});
it('falls back to request ip when X-Real-Ip is invalid or absent', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
$request = Request::create('/', 'GET', [], [], [], [
'HTTP_X_REAL_IP' => 'not-an-ip',
'REMOTE_ADDR' => '198.51.100.25',
]);
$this->app->instance('request', $request);
$this->app->forgetInstance('clientIp');
// WHEN
$clientIp = $this->app->make('clientIp');
// THEN
expect($clientIp)->toBe('198.51.100.25');
});
it('trusts X-Forwarded-For and ignores RFC 7239 Forwarded header', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
$response = $this->withHeaders([
'X-Forwarded-For' => '203.0.113.99',
'Forwarded' => 'for=198.51.100.77',
])->get('/');
// WHEN
$resolvedIp = request()->ip();
// THEN
$response->assertStatus(200);
expect($resolvedIp)->toBe('203.0.113.99');
});
});